Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Mail is not supporting UTF-8 Characters in Subject of the email

Tags:

java

Here is my code of setting subject to the email:

  String bodyMessage="Dear Renavçilçleç Françoisç InCites™";
  String subject = "Your new InCites™ subscription";

  Properties _sessionProperties = new Properties();
  _sessionProperties.put("mail.transport.protocol", "smtp");
  _sessionProperties.put("mail.smtp.host", "hostname");
  _sessionProperties.put("mail.smtp.port", "25");

  Session session = Session.getInstance(_sessionProperties, null);

  MimeMessage mimemsg = new MimeMessage(session);
  mimemsg.addRecipients(Message.RecipientType.TO, "[email protected]");
  mimemsg.setSubject(subject, "UTF-8");

  // Create a multi-part message
  MimeMultipart multipart = new MimeMultipart();
  // Set the subType
  multipart.setSubType("alternative");
  BodyPart part = new MimeBodyPart();

  part.setContent(bodyMessage, "charset=UTF-8");

  // Set the emailBody and emailType to MIME BodyPart
  part.setDataHandler(new DataHandler(new ByteArrayDataSource(
      bodyMessage, "text/html;")));

  // Add the MIME BodyPart to MIME multiPart
  multipart.addBodyPart(part);

  // Put parts in message
  mimemsg.setContent(multipart);

  // Send message
  Transport.send(mimemsg);

But still in email subject it still shows as "Your new InCites™ subscription"

like image 550
Kalyan Raju Avatar asked Dec 10 '10 07:12

Kalyan Raju


1 Answers

The subject you mention here consists completely of ASCII characters. This includes the funny special characters ™. If you want it to be Unicode, just use Unicode and not the HTML-escaping. Mails don't have anything to do with HTML.

mimemsg.setSubject("Your new InCites\u2122 subscription", "UTF-8");

This should encode the subject as something like =?UTF-8?Q?Your...subscription?=, as specified in RFC 2047.

The complete example code:

package so4406538;

import java.io.IOException;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

public class MailDemo {

  public static void main(String[] args) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);
    message.setSubject("Your new InCites\u2122 subscription", "UTF-8");
    message.setContent("hello", "text/plain");
    message.writeTo(System.out);
  }
}

The output:

Message-ID: <7888229.0.1291967222281.JavaMail.roland@bacc>
Subject: =?UTF-8?Q?Your_new_InCites=E2=84=A2_subscription?=
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

hello

You can see that the subject header is encoded, and this is necessary and correct.

[Update: I fixed the Unicode escape sequence, as indicated in one of my comments.]

like image 173
Roland Illig Avatar answered Oct 06 '22 18:10

Roland Illig