JavaMail附件中文名称乱码

原帖地址:
JavaMail附件中文名称乱码 - Different Design Studio - 博客频道 - CSDN.NET http://blog.csdn.net/fireson/article/details/7095948

问题: 用Javamail发邮件到邮件服务器,从邮箱中查看发现附件的中文名称变成了密码

原因:不明

解决:在设置邮件附件的时候调用javax.mail.internet.MimeUtility 来编码, 例如


MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);

// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(msgText1);

// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();

// attach the file to the message
mbp2.attachFile(filePath);
mbp2.setFileName(MimeUtility.encodeWord(fileName));

// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);

// add the Multipart to the message
msg.setContent(mp);

// set the Date: header
msg.setSentDate(new Date());

/*
* If you want to control the Content-Transfer-Encoding of the
* attached file, do the following. Normally you should never need
* to do this.
*
* msg.saveChanges(); mbp2.setHeader("Content-Transfer-Encoding",
* "base64");
*/

// send the message
Transport.send(msg);


你可能感兴趣的:(java)