位置:首頁 > Java技術 > Java教學 > Java發送Email/郵件

Java發送Email/郵件

使用Java應用程序發送郵件是很簡單的,需要安裝JavaMail API 和Java Activation Framework (JAF) 在機器上。

下載並解壓縮這些文件,在新創建的頂層目錄,會發現一些jar文件應用。需要添加了mail.jar和activation.jar文件在CLASSPATH中。

發送一個簡單的E-mail:

下麵是一個例子,從機器發送一個簡單的電子郵件。這裡假設你的電腦已經可以連接到互聯網,並有足夠的能力來發送電子郵件。

// 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....

如果想發送電子郵件給多個收件人,然後下麵的方法將被用來指定多個電子郵件標識:

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

這裡的參數的說明:

  • type: 這將被設定為TO,CC或BCC。在這裡,CC代表抄送和BCC代表黑抄送。例子Message.RecipientType.TO

  • addresses: 這是電子郵件的ID的數組。需要使用InternetAddress() 方法,同時指定電子郵件ID

Send an HTML E-mail:

下麵是一個例子,從機器發送的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");

郵件發送機製的其餘部分將繼續如上麵所述。