JavaMail API 傳送電子郵件帶有附件


下面是一個例子從你的機器上選擇附件傳送電子郵件。放置到 /home/manisha/ 在本地機器上的 file.txt檔案。在這裡,我們使用JangoSMPT伺服器通過該電子郵件被傳送到我們的目標電子郵件地址。 

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

  • 獲得一個對談 Session

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

  • 實際的訊息如下:

    messageBodyPart.setText("This is message body");
  • 建立一個MimeMultipart的物件。新增上述messageBodyPart與實際的訊息在其設定,這個多重物件。

  • 接下來建立一個DataHandler的如下新增附件:

    messageBodyPart = new MimeBodyPart();
    String filename = "/home/manisha/file.txt";
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
  • 接下來設定多重如下訊息中:

    message.setContent(multipart);
  • 傳送使用傳輸物件的訊息。

建立Java類

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

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.Multipart;
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 SendAttachmentInEmail {
   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");

      // Get the Session object.
      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");

         // Create the message part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Now set the actual message
         messageBodyPart.setText("This is message body");

         // Create a multipar message
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);

         // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "/home/manisha/file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);

         // Send the complete message parts
         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類用於驗證的密碼。

編譯並執行

現在,我們班是準備好了,讓我們編譯上面的類。我已經儲存了類SendAttachmentInEmail.java到目錄:/home/manisha/JavaMailAPIExercise.我們需要的jar檔案:javax.mail.jar和activation.jar檔案在classpath。執行下面的命令從命令提示字元編譯類(兩個jar被放置在/home/manisha/ 目錄下): 

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

現在,這個類被編譯,執行下面的命令來執行:

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

驗證輸出

你應該看到下面的訊息命令控制台上:

Sent message successfully....

因為我通過JangoSMTP傳送郵件到我的Gmail地址,下面的郵件會在我的Gmail帳戶的收件箱中接收:

JavaMail API Send Email With Attachment