JavaMail API - 发送包含内嵌图片的邮件



这是一个从您的计算机发送包含内嵌图片的 HTML 邮件的示例。我们在这里使用了 JangoSMTP 服务器来发送邮件到我们的目标邮箱地址。设置方法在环境设置章节中解释。

要发送包含内嵌图片的邮件,请按照以下步骤操作:

  • 获取会话

  • 创建一个默认的 MimeMessage 对象,并在邮件中设置发件人收件人主题

  • 创建一个 MimeMultipart 对象。

  • 在我们的示例中,邮件将包含 HTML 部分和一个图片。所以首先创建 HTML 内容,并将其设置为多部件对象:

    // 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);
    
  • 接下来,通过创建 Datahandler 添加图片,如下所示:

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource(
     "/home/manisha/javamail-mini-logo.png");
    
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");
    
  • 接下来,按如下方式设置邮件中的多部件:

    message.setContent(multipart);
    
  • 使用 Transport 对象发送邮件。

创建 Java 类

创建一个名为SendInlineImagesInEmail的 Java 类文件,其内容如下:

package com.tutorialspoint;

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendInlineImagesInEmail {
   public static void main(String[] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";

      // Sender's email ID needs to be mentioned
      String from = "[email protected]";
      final String username = "manishaspatil";//change accordingly
      final String password = "******";//change accordingly

      // Assuming you are sending email through relay.jangosmtp.net
      String host = "relay.jangosmtp.net";

      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", "25");

      Session session = Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(username, password);
            }
         });

      try {

         // Create a default MimeMessage object.
         Message message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));

         // Set Subject: header field
         message.setSubject("Testing Subject");

         // This mail has 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(
            "/home/manisha/javamail-mini-logo.png");

         messageBodyPart.setDataHandler(new DataHandler(fds));
         messageBodyPart.setHeader("Content-ID", "<image>");

         // add image to the multipart
         multipart.addBodyPart(messageBodyPart);

         // put everything together
         message.setContent(multipart);
         // Send message
         Transport.send(message);

         System.out.println("Sent message successfully....");

      } catch (MessagingException e) {
         throw new RuntimeException(e);
      }
   }
}

由于我们使用的是主机提供商 JangoSMTP 提供的 SMTP 服务器,我们需要验证用户名和密码。javax.mail.PasswordAuthentication 类用于验证密码。

编译和运行

现在我们的类已准备就绪,让我们编译上面的类。我已经将 SendInlineImagesInEmail.java 类保存到目录:/home/manisha/JavaMailAPIExercise。我们需要在类路径中包含 javax.mail.jaractivation.jar。从命令提示符执行以下命令来编译类(两个 jar 文件都位于 /home/manisha/ 目录下):

javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail.java

现在类已编译,执行以下命令运行:

java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail

验证输出

您应该在命令控制台中看到以下消息:

Sent message successfully....

由于我通过 JangoSMTP 向我的 Gmail 地址发送邮件,因此我的 Gmail 帐户收件箱中将收到以下邮件:

JavaMail API Send Email With Inline Images
javamail_api_sending_emails.htm
广告