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?

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章