使用Java程式傳送電子郵件


使用Java應用程式傳送電子郵件非常簡單,但首先你應該在你的機器上安裝**JavaMail API**和**Java Activation Framework (JAF)**。

下載並解壓這些檔案,在新建立的頂級目錄中,你會找到這兩個應用程式的許多jar檔案。你需要將**mail.jar**和**activation.jar**檔案新增到你的CLASSPATH中。

傳送簡單的電子郵件

這是一個從你的機器傳送簡單電子郵件的例子。假設你的**本地主機**已連線到網際網路,並且能夠傳送電子郵件。

示例

// File Name SendEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {

   public static void main(String [] args) {
   
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

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

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

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

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

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

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

編譯並執行此程式以傳送簡單的電子郵件:

輸出

$ java SendEmail
Sent message successfully....

如果你想向多個收件人傳送電子郵件,則可以使用以下方法指定多個電子郵件ID:

void addRecipients(Message.RecipientType type, Address[] addresses)
   throws MessagingException

以下是引數的說明:

  • **type** - 這將設定為TO,CC或BCC。其中CC代表抄送,BCC代表密送。例如:Message.RecipientType.TO

  • **addresses** - 這是一個電子郵件ID陣列。在指定電子郵件ID時,需要使用InternetAddress()方法。

傳送HTML電子郵件

這是一個從你的機器傳送HTML電子郵件的例子。假設你的**本地主機**已連線到網際網路,並且能夠傳送電子郵件。

此示例與前一個示例非常相似,不同之處在於我們在這裡使用setContent()方法來設定內容,其第二個引數是“text/html”,用於指定郵件中包含HTML內容。

使用此示例,你可以傳送任意大小的HTML內容。

示例

// File Name SendHTMLEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendHTMLEmail {

   public static void main(String [] args) {
   
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

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

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

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

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Send the actual HTML message, as big as you like
         message.setContent("<h1>This is actual message</h1>", "text/html");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

編譯並執行此程式以傳送HTML電子郵件:

輸出

$ java SendHTMLEmail
Sent message successfully....

傳送電子郵件附件

這是一個從你的機器傳送包含附件的電子郵件的例子。假設你的**本地主機**已連線到網際網路,並且能夠傳送電子郵件。

示例

// File Name SendFileEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendFileEmail {

   public static void main(String [] args) {     
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

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

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

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

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

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

         // Fill the 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 = "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 mex) {
         mex.printStackTrace();
      }
   }
}

編譯並執行此程式以傳送HTML電子郵件:

輸出

$ java SendFileEmail
Sent message successfully....

使用者身份驗證部分

如果需要向電子郵件伺服器提供使用者ID和密碼進行身份驗證,則可以按如下方式設定這些屬性:

props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

其餘的電子郵件傳送機制將與上面解釋的相同。

更新於:2019年7月30日

508 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告