Java Mail does not support UTF-8 characters in the subject line

Here is my setup code to be written:

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, "xxx@gmail.com"); 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 the subject line, it still appears as "Your new InCites™ subscription"

+7
java
source share
1 answer

The theme you mentioned here is made up entirely of ASCII characters. This includes funny special characters ™ . If you want it to be Unicode, use Unicode rather than HTML escaping. Letters have nothing to do with HTML.

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

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

Full code example:

 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); } } 

Exit:

 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 topic title is encoded, and this is necessary and correct.

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

+13
source share

All Articles