Java Mail 如何发送包含有Image的邮件

使用Java Mail发送包含有image的邮件时,有如下两种实现方式。

1. 在邮件的正文中,使用<img>标签,使其的src属性指向到服务器上的一个image文件,如下所示。当用户查看邮件时,对于包含的图片文件,邮箱会到图片文件所在服务器上下载图片文件,并显示到邮件中。

MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML  mail with images");
message.setFrom(new InternetAddress("[email protected]"));
message.setContent("<h1>This is a test</h1>" 
           + "<img src=\"http://www.rgagnon.com/images/jht.gif\">", 
           "text/html");

 

2. 把image作为附件发送,之后在邮件中使用cid前缀和附件的content-id来显示图片。因为这种方式直接把图片文件作为附件发送了,使得邮件变大了。好处是,邮箱不需要再去下载图片文件显示了。

MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML  mail with images");
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

// This HTML mail have to 2 part, the BODY and the embedded image
MimeMultipart multipart = new MimeMultipart("related");

// first part  (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");

// add it
multipart.addBodyPart(messageBodyPart);
        
// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("C:\\images\\jht.gif");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");

// add it
multipart.addBodyPart(messageBodyPart);

// put everything together
message.setContent(multipart); 

 

详细参见下面的文章:

Send HTML mail with images (Javamail)

 

对于邮件中的图片无法正常显示的原因分析,详细参见下面的文章:

Why don't pictures show up in the emails I send or receive?

 

 

你可能感兴趣的:(java mail)