1.把邮件保存为一个文件,这个文件可以直接用Outlook,FoxMail等邮件客户端工具打开。
private void savemail(MimeMessage msg, String path) {
try {
File f = new File(path);
f.getParentFile().mkdirs();
FileOutputStream fo = new FileOutputStream(f);
//CRLFOutputStream 可以把一些换行符不满足MIME规范的邮件进行修正。
CRLFOutputStream CRLFO = new CRLFOutputStream(fo);
msg.writeTo(CRLFO);
CRLFO.close();
fo.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
调用:
savemail(msg,"c:/lizongbo/testmail.eml");
2.对邮件体使用base64编码。
默认情况下使用的是quoted-printable编码:
示例如下:
MimeMessage msg = new MimeMessage((Session)null);
msg.setFrom(new InternetAddress("lizongbo@gmail.com"));
msg.setRecipient(Message.RecipientType.TO,
new InternetAddress("lizongbo@MSN.com"));
msg.setText("测试一下,邮件来自 http://www.donews.net/lizongbo !!!");
msg.setSubject("测试标题!!!", "GB2312");
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart txtbodyPart = new MimeBodyPart();
txtbodyPart.setText("这是一封Html邮件,请用HTML方式察看!!!");
multipart.addBodyPart(txtbodyPart);
MimeBodyPart HTMLodyPart = new MimeBodyPart();
String content="HTML邮件内容!来自 http://www.donews.net/lizongbo ";
content = "<HTML><body>" + content + "</body><HTML>";
HTMLodyPart.setContent(content, "text/HTML;charset=GBK");
multipart.addBodyPart(HTMLodyPart);
msg.setContent(multipart);
msg.saveChanges();
得到的邮件内容为:
--------------------------------------------------------------
Message-ID: <32591083.1110043294640.JavaMail.lizongbo@localhost>
From: lizongbo@gmail.com
To: lizongbo@msn.com
Subject: =?GB2312?B?suLK1LHqzOKjoaOho6E=?=
Mime-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part_0_8568863.1110043294484"
------=_Part_0_8568863.1110043294484