从java邮件发送支持Outlook的HTML邮件正文

时间:2013-03-11 11:19:09

标签: java html email

我使用的代码在浏览器中运行良好,但在Outlook中显示的格式不正确:

MimeMultipart mimeMultipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();

bodyPart.setText("<html><body><font size='3px' face='Times New Roman'>"
    + removeMultipleSpaces(msgbody) + "</font></body></html>");
mimeMultipart.addBodyPart(bodyPart);
bodyPart.setDescription("Text");
bodyPart.setHeader("Content-Type", "text/html; charset=utf-8" );

1 个答案:

答案 0 :(得分:0)

正如您在评论中提到的,您想要添加图片。为图像创建一个MimeBodyPart,创建一个cid,并在图像的MimeBodyPart上执行setContentID:

import javax.mail.internet.*;

MimeMultipart content = new MimeMultipart("related");

MimeBodyPart mainPart = new MimeBodyPart();
mainPart.setText("<html><body><img src=\"cid:123456789@localhost\"></body></html>","UTF-8", "html");
content.addBodyPart(mainPart);

MimeBodyPart imagePart = new MimeBodyPart();

java.net.URL img1 = Example.class.getClassLoader().getResource("image.png");
imagePart.setDataHandler(new DataHandler(img1));
//or:
//imagePart.attachFile("resources/image.png");

imagePart.setContentID("<123456789@localhost>");   // to embed
imagePart.setDisposition(MimeBodyPart.INLINE);  // to embed
content.addBodyPart(imagePart);