Tomcat编码问题与电子邮件

时间:2017-02-17 06:46:54

标签: java email encoding utf-8 tomcat7

我在Windows Tomcat上部署了一个java webapp,我已经对将字符编码设置为UTF-8进行了所有更改,并且它适用于所有请求响应。但问题是垃圾字符出现在使用webapp发送的电子邮件中。

解决问题需要做些什么?

电子邮件服务代码:

SimpleMailMessage msg = new SimpleMailMessage();
Map<String, Object> model = new HashMap<String, Object>();
model.put("userName", StringEscapeUtils.unescapeJava(StringEscapeUtils.unescapeHtml(name)));
StringWriter writer = new StringWriter();
        VelocityEngineUtils.mergeTemplate(velocityEngine, "vm/messages/create_user.vm", "utf-8", model, writer);
        msg.setText(writer.toString());
this.mailSender.send(msg);

邮件中的垃圾字符示例:

  Hallo P?ajwal Thakare,

     

Sie erhalten diese automatische E-Mail,da SiedasZurücksetzenIhres   Passworts angefordert haben。

这里P?ajwal应该是邮件中的Pʁajwal

1 个答案:

答案 0 :(得分:0)

将SimpleMailMessage替换为MimeMessage。现在您可以设置UTF-8字符集。

MimeMessage msg = mailSender.createMimeMessage();

msg.addRecipient(RecipientType.TO, new InternetAddress(adminEmail));
msg.addFrom(new InternetAddress[] { new InternetAddress(adminEmail) });

msg.setSubject(subject, "UTF-8");
msg.setText(message, "UTF-8");  
mailSender.send(msg);

有关详细信息,请参阅here