Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with subject encoding when sending an email

I'm sending an email and I'm receiving it correctly but the encoding of the subject is not correct. I'm sending "invitación" but I'm receiving "invitaci?n". The content of the message is OK.

The content of the message is coming from a transformation of a Velocity Template while the subject is set in a String variable.

I've googled around and I've seen that some people says that MimeUtility.encodeText() could solve the problem, but I have had no success with it.

How can I solve the problem? This is the code I have so far.

String subject = "Invitación";
String msgBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/vmTemplates/template.vm", "UTF-8", model);

Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);

try {
    String encodingOptions = "text/html; charset=UTF-8";
    Message msg = new MimeMessage(session);
    msg.setHeader("Content-Type", encodingOptions);
    msg.setFrom(new javax.mail.internet.InternetAddress(emailFrom));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));

    msg.setSubject(subject);
    msg.setContent(msgBody, encodingOptions);
    Transport.send(msg);

    } catch (AddressException e) {
        ...
    } catch (MessagingException e) {
        ...
    } 

Thanks

like image 608
Javi Avatar asked Feb 04 '11 12:02

Javi


3 Answers

JavaMail has perhaps a little too much abstraction, and you're falling victim to it here. When you use

Message msg = new MimeMessage(session);

you're creating a MimeMessage object but treating it as a Message object. Message has only a setSubject(String subject) method, which uses the platform default charset to encode the subject. If the platform default can't encode it, you get ? characters in the resulting header. MimeMessage, however, has a setSubject(String subject, String charset) method which will allow you to specify the charset you want to use to encode the subject. So just switch your code to

MimeMessage msg = new MimeMessage(session);
msg.setHeader("Content-Type", encodingOptions);
msg.setFrom(new javax.mail.internet.InternetAddress(emailFrom));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));

msg.setSubject(subject, "UTF-8");

and it should work.

like image 178
dkarp Avatar answered Nov 11 '22 07:11

dkarp


you can use, it works

msg.setSubject(MimeUtility.encodeText("string", "UTF-8", "Q"));
like image 21
Edy Aguirre Avatar answered Nov 11 '22 07:11

Edy Aguirre


Maybe you can try: msg.setSubject(subject, "UTF8");

like image 4
ksimon Avatar answered Nov 11 '22 07:11

ksimon