JavaMail 傳送電子郵件內嵌圖片


下面的一個例子,是從你的機器傳送HTML電子郵件,並內嵌影象。在這裡,我們使用JangoSMPT伺服器通過該電子郵件被傳送到我們的目標電子郵件地址。

要傳送電子郵件,其中包含一個內嵌的影象,遵循的步驟是:

  • 獲取一個Session

  • 建立一個預設的MimeMessage物件,並設定發件人,收件人,主題(From, To, Subject )在訊息中。

  • 建立一個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);
  • 傳送使用傳輸物件的訊息。

建立Java類

建立一個Java類檔案SendInlineImagesInEmail,是其內容如下:

package com.yiibai;

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.jar 和 activation.jar 檔案在 classpath 中。執行下面的命令從命令提示字元編譯類(兩個罐子被放置在/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