Internationalization issues: How to set UTF-8 with MimeMessage for email in Java

Writing by on Tuesday, 31 of January , 2012 at 9:50 pm

Content and subject for Chinese, Japanese, Korean (CJK) and other language characters showing up garbled or with question marks ????

Gosh! I know – What a pain! But, there’s a solution! Simply set the encoding to UTF-8 and not ISO8859_1 or any other encoding format.

Found a good post from Isocra Consulting that solves this issue.

Properties props = new Properties();
// put in your SMTP host in here
props.put("mail.smtp.host", "localhost");
Session s = Session.getInstance(props, null);

MimeMessage message = new MimeMessage(s);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setHeader("Content-Type", "text/plain; charset=UTF-8");
message.setSubject(subject, "UTF-8"); //IMPORTANT

// Either use setText() or setContent()
message.setText(body, "UTF-8"); //IMPORTANT 
// message.setContent(body, "text/plain; charset=UTF-8"); // ALTERNATIVELY USE THIS

Transport.send(message);

Leave a comment

Category: Java

No Comments

No comments yet.

Leave a comment

You must be logged in to post a comment.

Shivdev Kalambi's Blog

Shivdev Kalambi is a Software Development Manager, previously a Principal Software Engineer at ArcSight/HP. With over 16 years' experience in software development, he's worked on several technologies and played different roles and contributed to all phases of projects. Non-tech activies include Ping-pong, Rock Climbing and Yoga at PG, Golf, Skiing, Swimming & a beer enthusiast.