@Test
public void testEmailCharacterSet() throws MessagingException, UnsupportedEncodingException {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setDefaultEncoding("utf-8");
mailSender.setHost("*****");
mailSender.setUsername("*****");
mailSender.setPassword("*****");
Properties properties = new Properties();
properties.setProperty("mail.mime.charset", "utf-8");
mailSender.setJavaMailProperties(properties);
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8");
mimeMessage.setContent("Árvíztűrő tükörfúrógép 3", "text/html");
helper.setFrom("noreply@foobar.com");
helper.setTo("foobar@gmail.com");
mailSender.send(mimeMessage);
}
正如你所看到的那样,无论何时我都能设置utf-8。我的问题是传出的原始字节仍然是Latin1,至少这是我在Wireshark中看到的:
Date: Sun, 17 May 2015 18:16:21 +0200 (CEST)
From: noreply@foobar.com
To: foobar@gmail.com
Message-ID: <13648335.0.1431879381653.JavaMail.foo@foo-dell>
MIME-Version: 1.0
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
=C1rv=EDzt?r? t=FCk=F6rf=FAr=F3g=E9p 3
.
所以基本上标题都是UTF-8,但是外出字节已经包含问号,其中应该出现ő和,,这是Latin1中缺少的两个字符。 JVM的file.encoding
不是UTF-8,但我正在寻找一种保持原样的方法,只在电子邮件方面解决这个问题。
谢谢!
更新
我之前已成功使用普通的旧方法发送电子邮件,有趣的是,这仍然有效:
Message mimeMessage = new MimeMessage(session);
mimeMessage.setContent("Árvíztűrő tükörfúrógép 7 oldschool", "text/html; charset=utf-8");
因此,它显然仅适用于JavaMailSenderImpl
。
答案 0 :(得分:1)
如果添加以下行:
properties.setProperty("mail.smtp.allow8bitmime", "true");
properties.setProperty("mail.smtps.allow8bitmime", "true");
到您的代码,邮件将 Content-Transfer-Encoding:标头设置为 8bit ,邮件将可读。
答案 1 :(得分:1)
这对我有用-link
mailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws MessagingException {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setFrom("me@mail.com");
message.setTo("you@mail.com");
message.setSubject("my subject");
message.setText("my text <img src='cid:myLogo'>", true);
message.addInline("myLogo", new ClassPathResource("img/mylogo.gif"));
message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
}
});