---
title: "Java Mail 如何发送包含有Image的邮件"
author: "peterlij"
date: "2013-05-02T20:05:53Z"
tags: []
categories: ["Web前端"]
slug: "java-mail-image"
draft: false
lastmod: "2013-05-02T20:07:49Z"
id: 1858917
url: "https://peterlij.iteye.com/blog/1858917"
---

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

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

```
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML  mail with images");
message.setFrom(new InternetAddress("me@sender.com"));
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("me@sender.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("you@receiver.com"));

// 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)](http://www.rgagnon.com/javadetails/java-0504.html)

 

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

[Why don't pictures show up in the emails I send or receive?](http://ask-leo.com/why_dont_pictures_show_up_in_the_emails_i_send_or_receive.html)