JavaMail邮件主题乱码的解决方法
类别: JAVA教程
很多朋友都使用过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);
}
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);
}
- 上一篇: java图像浏览器
- 下一篇: JavaBean 设置关联属性
-= 资 源 教 程 =-
文 章 搜 索