JavaMail邮件主题乱码的解决方法
JavaMail中的邮件主题需要进行BASE64编码,
格式形如:
=?GB2312?B?xPq1xMPcwuvS0b6t1tjWw6Osx+u+ob/stcfCvKOssqLQ3rjEw9zC66Oh?=
所以,直接使用msg.setSubject("中文主题"),或者msg.setSubject("中文主题".getBytes("8859_1"), "GB2312"))都一样会出现乱码。
在设置邮件主题前需要将主题字串的字节编码为BASE64格式,并添加编码头,示例代码如下:
try{
String subject = "中华全国helloworld";
String content = "测试邮件中语言问题.helloworld";
Context ctx = new InitialContext();
if(ctx == null)
throw new Exception("NO Context()");
System.out.println(ctx);
javax.mail.Session mailsession = (javax.mail.Session)ctx.lookup("java:comp/env/mail/session");
System.out.println(mailsession);
Message msg = new MimeMessage(mailsession);
InternetAddress[] toAddrs = InternetAddress.parse("david.li@maxcard.com",false);
msg.setRecipients(Message.RecipientType.TO, toAddrs);
//msg.setSubject("=?GB2312?B?"+Base64.encode(subject.getBytes())+"?=");
//将中文转化为GB2312编码
subject = StringUtil.getString(subject, "GB2312");
subject = new String(Base64.encode((subject).getBytes()));
msg.setSubject("=?GB2312?B?" + subject + "?=");
msg.setFrom(new InternetAddress("david.li@maxcard.com"));
msg.setText(StringUtil.getString(content,"GB2312"));
//
Transport t = mailsession.getTransport("smtp");
t.send(msg);
out.println("成功");
//Transport.send(msg);
}catch(Exception e){
out.println("失败");
System.out.println(e);
}
Tags:
作者:佚名评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论