Link to home
Start Free TrialLog in
Avatar of caifan82
caifan82

asked on

Help with javamail

Hello everyone.

I have this really urgent question.
I am using javamail for sending HTML mailing lists, with JSPs. Almost everything is working fine.
However, there are times when i need to send mails whose subject has characters like "á, é, í, ó, ú, ñ, Ñ, ¿, ¡" (you know, those whose HTML encoding are á &eacute, etc...)
As you surely expect, when those characters (not their HTML encoding counterparts) are included in the subject and i send the emails, the subject gets all corrupted in the inboxes.

Anyone can help on how to solve this?

I would be very grateful if anybody could help asap.

Thank you!

Alain
Avatar of armoghan
armoghan
Flag of Pakistan image

Avatar of girionis
Java is unicode by default so you shouldn't have any problems. How do you know that the characters are not arriving correctly on the client but it cannot pront them properly? What happens if you print the characters before you send the e-mail? Do you see them correctly?
set system property to you JVM mail.smtp.allow8bitmime=true , eg:
java -Dmail.smtp.allow8bitmime=true your classname.

http://www.jguru.com/faq/view.jsp?EID=507286

also during setting subject use following API:
MimeMessage.setSubject(subject, "ISO-8859-1");
Avatar of caifan82
caifan82

ASKER

@girionis: I know the characters are not attiving correctly on the client, because one of the emails i am using is mine. When i check the result on my inbox, the subject is all corrupted. I already printed the results in my jsp, before sending the emails, and they are already corrupted. Any thoughts?
How do you generate the e-mail and the subject?
Ok:
I am using an HTML form in a JSP. This form has 3 fields: the subject (wich is a simple text field), the email (this one is a little bit trickier, since i am using a file field for uploading an HTML file that will serve as the email body) and the recipients for sending the emails (this one is a combo box).
The subject is manually entered by me in the text field, then i browse my PC (with the file field) for the HTML file that will serve as the email body. Finally, I select the recipients for the emails with the checkbox... and i click on send... the emails are all sent! But if i use characters like á,é,í, etc... on the subject, it gets all corrupted.
I already printed the subject with System.out, even before it has any chance to get to the "send emails" part, and they are already corrupted. So, now I'm thinking that the problem might be with my HTML form, wich has the following enctype: "enctype = "multipart/form-data", so that i can upload files. I don´t know. This might be a possibitlity, but still i dont know how to solve this.

I hope its a bit clearer now.

Help! ;)

> I already printed the subject with System.out, even before it has any chance to get to the "send emails" part, and they are already corrupted.

Right, where did you print it? In the console? You have to knwo that the console does *not* support unicode characters and even if they are correct you wil lstil lsee them corrupted. Is it possible instead of a System.out to print them to a file and then open this file from a unicode editor? Also what is the encoding you use for your JSP page?
well, i printed them in the console AND on another JSP page. The characters are corrupted on both cases.
Both JSP pages have the following encodings: <%@page pageEncoding="iso-8859-1"%>

I really appreciate your help, so far. Lets hope we'll make this work.

Thanx!
Ok, first things first, what happens if you change the encoding to match the encoding for your characters?
Ok. Let's go to the roots. Could you send JSP page source.
@girionis: isnt iso-8859-1 the right encoding for these characters? If not, wich is it?

@ramazanyich: ok, here you go: (i just removed some extra stuff that dont have anything to do, like javascripts... )

<%@page contentType="text/html"%>
<%@page pageEncoding="iso-8859-1"%>
<%@page import="java.net.URL"%>
<%@page import="java.net.URLEncoder"%>
<%@page import="java.net.URLConnection"%>
<%@page import="java.util.Vector"%>
<%@page import="java.io.DataOutputStream"%>
<%@page import="java.io.DataInputStream"%>
<%@page import="java.util.Properties" %>

<html>
<head>
<title>Administration</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<table align="center">
  <tr>
    <td>
      <div align="center">
        <p><font color ="#006699" size="-1" face="Verdana, Geneva, Arial, Helvetica, sans-serif"><strong>Administration</strong></font></p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
      </div></td>
  </tr>
  <tr>
    <td align = "center"><div align="center">
        <table border="0" align="left" cellpadding="1" cellspacing="0" bordercolor="#FFCC00" bgcolor="#FFFFFF">
          <tr>
            <td bgcolor="ffcc00"><font color="#006699" size="-1" face="Verdana, Geneva, Arial, Helvetica, sans-serif"><strong>Mailing lists</strong>:</font></td>
          </tr>
        </table>
      </div>
      <p align="center">&nbsp;</p>

      <form action="procesarforma.jsp" method="post" name="form1" enctype = "multipart/form-data">
        <table border="0" cellpadding="0" cellspacing="0" bordercolor="#FFCC00">
          <tr bgcolor="#FFFFFF">
            <td colspan="2"></td>
          </tr>
          <tr bgcolor="#FFFFFF">
            <td><font color="#000000" size="-1" face="Verdana, Geneva, Arial, Helvetica, sans-serif">Subject:</font></td>
            <td><input name="asunto" type="text" id="asunto" size="50"></td>
          </tr>
          <tr bgcolor="#FFFFFF">
            <td colspan="2"></td>
          </tr>
          <tr bgcolor="#FFFFFF">
            <td><font color="#000000" size="-1" face="Verdana, Geneva, Arial, Helvetica, sans-serif">HTML file:</font><font color="#006699" size="-1" face="Verdana, Geneva, Arial, Helvetica, sans-serif">:
              </font></td>
            <td><input type="file" name="file" size="50"></td>
          </tr>
          <tr bgcolor="#FFFFFF">
            <td colspan="2"></td>
          </tr>
          <tr bgcolor="#FFFFFF">
            <td> <p><font color="#006699" size="-1"><font color="#000000" face="Verdana, Geneva, Arial, Helvetica, sans-serif">Receivers: </font></font></p></td>
            <td><select name="example" size="1" onChange="redirect(this.options.selectedIndex)">
                <option>Everyone</option>
                <option>Medics</option>
                <option>Public</option>
              </select></td>
          </tr>
          <tr bgcolor="#FFFFFF">
            <td colspan="2"></td>
          </tr>
          <tr bgcolor="#FFFFFF">
            <td colspan="2">&nbsp;</td>
          </tr>
          <tr>
            <td colspan="2"> <p>&nbsp;</p>
              <table width="40%" border="0" align="center">
                <tr>
                  <td><div align="center">
                      <input type="submit" name="test" value="Enviar">
                    </div></td>
                  <td><div align="center">
                      <input type="button" name="test2" value="Cancelar" onclick="window.location='admonboletines.jsp'">
                    </div></td>
                </tr>
              </table>
              <br> <br>
             </td>
          </tr>
        </table>
      </form>

      <p>&nbsp; </p></td>
  </tr>
</table>
      </body>
</html>
> @girionis: isnt iso-8859-1 the right encoding for these characters? If not, wich is it?

Nope, ISO-8859-1 is latin. Form what I can see these characters are non-latin. What characters are they?
I have greek encoding and I can see them properly, are they greek or something else?
and source for procesarforma.jsp ?
@ girionis: Yeah, they are latin... á, é, í, ó, ú, ñ are all used in spanish, for example... Or, what encoding do you recomend?

@ramazanyich:
here you go: however, the subjects get corrupted just after i click send on the first JSP.

<%@page contentType="text/html"%>
<%@page pageEncoding="iso-8859-1"%>

<%@ page import="com.smart.sites.mailinglists.MailBean" %>
<%@ page import="com.smart.sites.mailinglists.DestinatarioBoletin" %>
<%@ page import="com.smart.sites.mailinglists.ProcesadorFormaMultipart"%>
<%@ page import="com.smart.sites.mailinglists.ArchivoEnForma"%>
<%@ page import="com.smart.sites.mailinglists.JakartaFileUploadProcesador"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.Vector" %>
<%@ page import="java.util.Properties" %>
<%@ page import="javax.mail.Session" %>
<%@ page import="javax.mail.Message" %>
<%@ page import="javax.mail.Address" %>
<%@ page import="javax.mail.Authenticator" %>
<%@ page import="javax.mail.Store" %>
<%@ page import="javax.mail.Folder" %>
<%@ page import="javax.mail.Transport" %>
<%@ page import="javax.mail.internet.MimeMessage" %>
<%@ page import="javax.mail.internet.InternetAddress" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.io.InputStreamReader" %>
<%@ page import="javax.mail.Multipart" %>
<%@ page import="javax.mail.BodyPart" %>
<%@ page import="javax.mail.internet.MimeMultipart" %>
<%@ page import="javax.mail.internet.MimeBodyPart" %>

<jsp:useBean id="selectEmails" class="com.smart.sites.mailinglists.MailBean"/>
<%
    String seleccionEmails = null;
    StringBuffer emailrecibidos = new StringBuffer();
    String mensajeemails = new String();
   
    boolean isMultipart = FileUpload.isMultipartContent(request);
    if ( isMultipart ) {
       
        ProcesadorFormaMultipart procesador= new JakartaFileUploadProcesador(request);
        ArchivoEnForma recibido = procesador.getArchivoEnForma();
        String asunto = procesador.getParametro("asunto");
        String etapa1 = procesador.getParametro("example");
        String contenido = recibido.getContenido();
        out.println("<html>");
        out.println("<head>");
        out.println("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=iso-8859-1\">");
        out.println("<title>Email sent</title>");
        out.println("</head>");
        out.println("<body bgcolor=#FFFFFF>");
        out.println("<table align=center width=90% border=1 cellpadding=0 cellspacing=0 bordercolor=#FFCC66 bgcolor=#FFFFFF>");
        out.println("   <tr>");
        out.println("       <td>");
        out.println("           <font color=#336699 size=-1 face=Verdana, Geneva, Arial, Helvetica, sans-serif>");
        out.println("               <strong>");
        out.println("                   Mailing lists::");
        out.println("               </strong>");
        out.println("           </font>");
        out.println("       </td>");
        out.println("   </tr>");
        out.println("</table>");
        out.println("<p>&nbsp;</p>");
        out.println("<table align=center width=90% border=1 cellpadding=0 cellspacing=0 bordercolor=#FFCC66 bgcolor=#FFFFFF>");
        out.println("   <tr>");
        out.println("       <td width=92% colspan=2>");
        out.println("           <p>");
        out.println("               <font color=#336699 size=-1 face=Verdana, Geneva, Arial, Helvetica, sans-serif>");
        out.println("                   <strong>");
        out.println("                       This email was sent:");
        out.println("                   </strong>");
        out.println("               </font>");
        out.println("           </p>");
        out.println("           <p>");
        out.println("               <strong>");
        out.println("                   <font color=#336699 size=-1 face=Verdana, Geneva, Arial, Helvetica, sans-serif>");
        out.println("                       Subject:");
        out.println("                   </font>");
        out.println("               </strong> ");
        out.println("                   <font color=#336699 size=-1 face=Verdana, Geneva, Arial, Helvetica, sans-serif>");
        out.println(asunto);
        out.println("                   </font>");
        out.println("           </p>");
        out.println("       </td>");
        out.println("   </tr>");
        out.println("   <tr>");
        out.println("       <td colspan=2>");
        out.println("           <div align=center>");
        out.println(contenido);
        out.println("           </div>");
        out.println("       </td>");
        out.println("   </tr>");
        out.println("</table>");
       
        mensajeemails = "No emails were sent.";
        MailBean selector = new MailBean();
        List dests = selector.select(etapa1, etapa2);
       
        for (Iterator i = dests.iterator(); i.hasNext(); ){
            Object obj = i.next();
            DestinatarioBoletin db = (DestinatarioBoletin)obj;
           
            try{
                    Properties props = new Properties();
                   
                    Session mailSession = Session.getDefaultInstance(props, null);
                   
                    MimeMessage message = new MimeMessage(mailSession);
                   
                    Multipart multipart = new MimeMultipart("alternative");

                    message.setSubject(asunto, "ISO-8859-1");
                   
                    BodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setText("Texto sin formato HTML");
                   
                    multipart.addBodyPart(messageBodyPart);
                   
                    messageBodyPart = new MimeBodyPart();
                    String htmlText = recibido.getContenido();
                    messageBodyPart.setContent(htmlText, "text/html");

                    multipart.addBodyPart(messageBodyPart);
                   
                    message.setContent(multipart);

                     Address address = new InternetAddress("darkness_insideme@yahoo.com.mx",
                        "Darkness Inside Me");
                     message.setFrom(address);

                     Address toAddress = new InternetAddress(db.getEmail());

                     message.addRecipient(Message.RecipientType.TO, toAddress);
                     
                     Transport.send(message);
                    mensajeemails = "Exitoso!";
                }catch(javax.mail.MessagingException me){
                    out.println(me.getMessage());
                    mensajeemails = me.getMessage();

                } catch(java.io.UnsupportedEncodingException uee){
                    out.println(uee.getMessage());
                    mensajeemails = uee.getMessage();
                }
            emailrecibidos.append("<p>" + db.getEmail() + "</p>");
            }
        }
%>

<br><br>
<table width="70%" border="1" align="center" cellpadding="5" cellspacing="0" bordercolor="#FFCC00" bgcolor="#FFFFFF">
  <tr>
    <td> <font color="#336699" size="-1" face="Verdana, Geneva, Arial, Helvetica, sans-serif"><strong>Recipients:</strong> <br>
      <%=emailrecibidos.toString()%> </font></td>
  </tr>
  <tr>
    <td> <font color="#336699" size="-1" face="Verdana, Geneva, Arial, Helvetica, sans-serif"><strong>Email status:</strong> <br>
      <%= mensajeemails %> </font></td>
  </tr>
</table>
</body>
</html>
Here is the JakartaFileUploadProcesador class:

package com.smart.sites.mailinglists;

import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import org.apache.commons.fileupload.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.http.HttpServletRequest;
import java.io.*;

public class JakartaFileUploadProcesador implements ProcesadorFormaMultipart{
   
    HashMap parametrosN = new HashMap();
    StringBuffer sb = new StringBuffer();
    String contentType = new String();
    ArchivoEnForma archivoEnForma = new ArchivoEnForma(sb, contentType);
   
    public JakartaFileUploadProcesador(HttpServletRequest request) {

        DiskFileUpload upload = new DiskFileUpload();

        try{
            List /* FileItem */ items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            int contador = 0;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {

                        String name = item.getFieldName();
                        String value = item.getString();
                        parametrosN.put(name, value);
                       
                        if(contador == 0){
                            FileOutputStream fout;            
                            try{
                                fout = new FileOutputStream ("subject.txt");
                                new PrintStream(fout).println (value);
                                fout.close();            
                            }catch (IOException e){
                                System.err.println ("Can´t write");
                            }
                        }
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    try{
                        InputStream uploadedStream = item.getInputStream();
                        InputStreamReader reader =  new InputStreamReader(uploadedStream);
                        int caracter = 0;
                        while ( (caracter = reader.read()) != -1){
                            char c = (char)caracter;
                            sb.append(c);

                        }
                        uploadedStream.close();    
                        reader.close();                      
                    }catch(java.io.IOException ioe){
                            System.out.println("<p>Can't get the content of the file<br/>"
                            + ioe.getMessage() + "</p>");
                    }
                    ArchivoEnForma archivoEnForma = new ArchivoEnForma(sb, contentType);
                }
                contador++;
            }
            return;                
            }catch(org.apache.commons.fileupload.FileUploadException fue){
                    System.out.println("Can't parse the request"
                    + fue.getMessage());
            }
    }
   
    public ArchivoEnForma getArchivoEnForma() {
        return archivoEnForma;
    }
   
    public String getParametro(String k) {
        return (String)parametrosN.get(k);
    }
   
}




And ArchivoEnForma:

package com.smart.sites.mailinglists;

public class ArchivoEnForma {
    public StringBuffer contenido = new StringBuffer();
    public String tipoContenido = new String();
    public String contenidoNormalizado = new String();
   
    public ArchivoEnForma(StringBuffer sb, String tc) {
        contenido = sb;
        tipoContenido = tc;        
    }

    public String getContenido() {
        return contenido.toString();
    }

    public String getTipoContenido(){
        return tipoContenido;
    }
   
}


Hope this might help to find a solution....
>@ girionis: Yeah, they are latin... ?, ?, ?, ?, ?, ? are all used in spanish, for example...
>Or, what encoding do you recomend?

Yes you are right, ISO-8859-1 does support spanish characters. Can you try, just to be sure, also Cp1145 or Cp284? Or even Unicode?

>@ramazanyich:
>here you go: however, the subjects get corrupted just after i click send on the first JSP.

What is the encoding of the first page? Is it the same?
Ok, i tried with Cp1145, Cp284 and unicode... i am getting different characters, but still they are all corrupted...

The encoding in every JSP is the same: iso-8859-1 (check the code i just submitted for both JSPs).

Mmm, i dont know what to do... please, any more thoughts?

Thanx
What is the encoding of the first page?
its also iso-8859-1, i posted the code of the whole first page some posts above...
Weird... What is the encoding of the browser?
Spanish...
Couldnt it be maybe some incompatibility with the application server? With weblogic 6, the subject gets all corrupted... but i tried with tomcat 5 and th subject apperas correctly. I´m thinking it could have something to do with the locales...
Do you know how to "control" this? How can i make weblogic 6 to use a locale compatible with spanish characters...
I don't know...
I'm running out of ideas...
If it works on Tomcat then it is probably an application server problem. I am also using WLS but I am curently away from my office. Check the properties for the web application from the console, there definetely is some option for the encoding. I remember this because I did it for greek encoding.
Ok, i checked but i can't find any options for the encoding of the web application. Where is it?
Can't this problem be solved by using java.util.locale? I have never used it, but isnt there anyway it might work? If it might, do you happen to know how to use it?
There should be something, check the servlets options or the general web applicaiton options.

> Can't this problem be solved by using java.util.locale? I have never used it, but isnt there anyway it might work? If it
>might, do you happen to know how to use it?

I am not sure if it would help. Locale is for localization the user still has to have the browser settings correct.
I think it consists on adding some tag to the weblogic.xml file.
However i dont have one, and i dont know how to make one... Can you help on this?
if you find your Headere in Mail as following

From: =?iso-8859-1?q?My=20Name?= <myname@mail.server.com>

Then this header is splited as

?iso-8859-1 - Character set
?q Encoding type (Q-Quoted printable, B-Base64)
?My=20Name?= <myname@mail.server.com> - Header value
This is a part of my weblogic.xml file for the greek characters (ISO-8859-7). Modify it accordingly.

<charset-params>
            <input-charset>
                  <resource-path>/*</resource-path>
                  <java-charset-name>ISO8859_7</java-charset-name>
            </input-charset>
            <charset-mapping>
                  <iana-charset-name>ISO-8859-7</iana-charset-name>
                  <java-charset-name>ISO8859_7</java-charset-name>
            </charset-mapping>
      </charset-params>
Ok, i created a weblogic.xml file on my WEB-INF folder...
It´s this one:

<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 6.0//EN"
  "http://www.bea.com/servers/wls610/dtd/weblogic-web-jar.dtd">
<weblogic-web-app>
      <charset-params>
            <input-charset>
                  <resource-path>/*</resource-path>
                  <java-charset-name>ISO8859_1<java-charset-name>
            </input-charset>
            <charset-mapping>
                  <iana-charset-name>ISO_8859-1:1987</iana-charset-name>
                  <java-charset-name>ISO-8859-1</java-charset-name>
            </charset-mapping>                        
      </charset-params>
</weblogic-web-app>

However, when i deploy it, and i try to access any JSPs on the WAR, i only get "File not found" messages... What is wrong with my weblogic.xml file? Is there something missing? I'm sorry, but i have never used one...
ooops, sorry, its this one:

<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 6.0//EN"
  "http://www.bea.com/servers/wls610/dtd/weblogic-web-jar.dtd">
<weblogic-web-app>
     <charset-params>
          <input-charset>
               <resource-path>/*</resource-path>
               <java-charset-name>ISO8859_1<java-charset-name>
          </input-charset>
          <charset-mapping>
               <iana-charset-name>ISO-8859-1</iana-charset-name>
               <java-charset-name>ISO8859_1</java-charset-name>
          </charset-mapping>                    
     </charset-params>
</weblogic-web-app>
Where does the "File not found" message refer to?
oh, ok... nevermind, i found the problem

Ok, now when i introduce anything in the subject, i am not getting the characters all corrupted, now i am getting nulls (with the subject and ht HTML file body)...
Why is this happening?
What do you mean null? null value or the string "null"?
>>Ok, now when i introduce anything in the subject, i am not getting the characters all corrupted, now i am getting nulls (with the subject and ht HTML file body)...

could u plz elaborate?
Ok, it seems that i solved the null value problem...
Now, i have my weblogic.xml file with the tags you suggested girionis (just edited to work with ISO-8859-1)... and the characters still get all corrupted!
I don't know what else to do... any ideas?
What happens if you try UTF8 instead if ISO8859_1 in your weblogic.xml?
Hey,
well, they still get corrupted... however the corruption is different...

This is so weird...
What is the difference this time? Maybe it will help us identify the problem.
well, with ISO-8859-1 i received "?" for every unrecognized character....
With UTF-8, i get a accented "y" (ý) for every unrecognized character...

You think this might help?
Hmm... I am not sure what's going on. How do you send the data to the next page? Via GET or POST? Is it possible to try and encode it using the URLEncoder.encode() method?
I send the data via POST...
Ok try something else. Try this:

OutputStream out = response.getOutputStream();
out = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
out.println(<your parameter here>);

and tell me if this helps at all.

Also, try this one too, try setting the locale (you had also suggested it but now it is the last resort), maybe it will help:

response.setLocale(new java.util.Locale("<your locale here>"));
Try the above for the charset ISO-8859-1, not for UTF-8
Hello,
well, that might solve the printing of the subject field... but... it would still be sent all corrupted, wouldnt it?
ASKER CERTIFIED SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Well, it still won't work.
I don't know what else can be done, and it seems we are not going to find a solution.
As a thank you for trying to help me so mucho, im gonna to award you the points anyway.
Thanks for trying!

Cheers!