Java 發送郵件,java發送郵件

來源:互聯網
上載者:User

Java 發送郵件,java發送郵件

使用Java應用程式發送E-mail十分簡單,但是首先你應該在你的機器上安裝JavaMail API 和Java Activation Framework (JAF) 。

你可以在 JavaMail (Version 1.2) 下載最新的版本。

你可以再 在JAF (Version 1.1.1)下載最新的版本。

下載並解壓這些檔案,最上層檔案夾你會發現很多的jar檔案。你需要將mail.jar和activation.jar 添加到你的CLASSPATH中。

如果你使用第三方郵件伺服器如QQ的SMTP伺服器,可查看文章底部使用者認證完整的執行個體。

發送一封簡單的 E-mail

下面是一個發送簡單E-mail的例子。假設你的localhost已經串連到網路。

// 檔案名稱 SendEmail.java import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendEmail{   public static void main(String [] args)   {         // 收件者電子郵箱      String to = "abcd@gmail.com";       // 寄件者電子郵箱      String from = "web@gmail.com";       // 指定發送郵件的主機為 localhost      String host = "localhost";       // 擷取系統屬性      Properties properties = System.getProperties();       // 設定郵件伺服器      properties.setProperty("mail.smtp.host", host);       // 擷取預設session對象      Session session = Session.getDefaultInstance(properties);       try{         // 建立預設的 MimeMessage 對象         MimeMessage message = new MimeMessage(session);          // Set From: 頭部頭欄位         message.setFrom(new InternetAddress(from));          // Set To: 頭部頭欄位         message.addRecipient(Message.RecipientType.TO,                                  new InternetAddress(to));          // Set Subject: 頭部頭欄位         message.setSubject("This is the Subject Line!");          // 設定訊息體         message.setText("This is actual message");          // 發送訊息         Transport.send(message);         System.out.println("Sent message successfully....");      }catch (MessagingException mex) {         mex.printStackTrace();      }   }}

編譯並運行這個程式來發送一封簡單的E-mail:

$ java SendEmailSent message successfully....

如果你想發送一封e-mail給多個收件者,那麼使用下面的方法來指定多個收件者ID:

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

下面是對於參數的描述:

  • type:要被設定為TO, CC 或者BCC. 這裡CC 代表抄送、BCC 代表秘密抄送y. 舉例:Message.RecipientType.TO

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

發送一封HTML E-mail

下面是一個發送HTML E-mail的例子。假設你的localhost已經串連到網路。

和上一個例子很相似,除了我們要使用setContent()方法來通過第二個參數為"text/html",來設定內容來指定要發送HTML內容。

// 檔案名稱 SendHTMLEmail.java import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendHTMLEmail{   public static void main(String [] args)   {           // 收件者電子郵箱      String to = "abcd@gmail.com";       // 寄件者電子郵箱      String from = "web@gmail.com";       // 指定發送郵件的主機為 localhost      String host = "localhost";       // 擷取系統屬性      Properties properties = System.getProperties();       // 設定郵件伺服器      properties.setProperty("mail.smtp.host", host);       // 擷取預設的 Session 對象。      Session session = Session.getDefaultInstance(properties);       try{         // 建立預設的 MimeMessage 對象。         MimeMessage message = new MimeMessage(session);          // Set From: 頭部頭欄位         message.setFrom(new InternetAddress(from));          // Set To: 頭部頭欄位         message.addRecipient(Message.RecipientType.TO,                                  new InternetAddress(to));          // Set Subject: 頭欄位         message.setSubject("This is the Subject Line!");          // 發送 HTML 訊息, 可以插入html標籤         message.setContent("<h1>This is actual message</h1>",                            "text/html" );          // 發送訊息         Transport.send(message);         System.out.println("Sent message successfully....");      }catch (MessagingException mex) {         mex.printStackTrace();      }   }}

編譯並運行此程式來發送HTML e-mail:

$ java SendHTMLEmailSent message successfully....
發送帶有附件的 E-mail

下面是一個發送帶有附件的 E-mail的例子。假設你的localhost已經串連到網路。

// 檔案名稱 SendFileEmail.java import java.util.*;import javax.mail.*;import javax.mail.internet.*;import javax.activation.*; public class SendFileEmail{   public static void main(String [] args)   {           // 收件者電子郵箱      String to = "abcd@gmail.com";       // 寄件者電子郵箱      String from = "web@gmail.com";       // 指定發送郵件的主機為 localhost      String host = "localhost";       // 擷取系統屬性      Properties properties = System.getProperties();       // 設定郵件伺服器      properties.setProperty("mail.smtp.host", host);       // 擷取預設的 Session 對象。      Session session = Session.getDefaultInstance(properties);       try{         // 建立預設的 MimeMessage 對象。         MimeMessage message = new MimeMessage(session);          // Set From: 頭部頭欄位         message.setFrom(new InternetAddress(from));          // Set To: 頭部頭欄位         message.addRecipient(Message.RecipientType.TO,                                  new InternetAddress(to));          // Set Subject: 頭欄位         message.setSubject("This is the Subject Line!");          // 建立訊息部分         BodyPart messageBodyPart = new MimeBodyPart();          // 訊息         messageBodyPart.setText("This is message body");                 // 建立多重訊息         Multipart multipart = new MimeMultipart();          // 設定簡訊部分         multipart.addBodyPart(messageBodyPart);          // 附件部分         messageBodyPart = new MimeBodyPart();         String filename = "file.txt";         DataSource source = new FileDataSource(filename);         messageBodyPart.setDataHandler(new DataHandler(source));         messageBodyPart.setFileName(filename);         multipart.addBodyPart(messageBodyPart);          // 發送完整訊息         message.setContent(multipart );          //   發送訊息         Transport.send(message);         System.out.println("Sent message successfully....");      }catch (MessagingException mex) {         mex.printStackTrace();      }   }}

編譯並運行你的程式來發送一封帶有附件的郵件。

$ java SendFileEmailSent message successfully....
使用者認證部分

如果需要提供使用者名稱和密碼給e-mail伺服器來達到使用者認證的目的,你可以通過如下設定來完成:

 props.put("mail.smtp.auth", "true"); props.setProperty("mail.user", "myuser"); props.setProperty("mail.password", "mypwd");

e-mail其他的發送機制和上述保持一致。

需要使用者名稱密碼驗證郵件發送執行個體:

本執行個體以QQ郵件伺服器為例,你需要在登入QQ郵箱後台在"設定"=》帳號中開啟POP3/SMTP服務 ,如所示:

 

Java 代碼如下:

// 需要使用者名稱密碼郵件發送執行個體//檔案名稱 SendEmail2.java//本執行個體以QQ郵箱為例,你需要在qq後台設定import java.util.Properties;import javax.mail.Authenticator;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.MimeMessage;public class SendEmail2{   public static void main(String [] args)   {      // 收件者電子郵箱      String to = "xxx@qq.com";      // 寄件者電子郵箱      String from = "xxx@qq.com";      // 指定發送郵件的主機為 localhost      String host = "smtp.qq.com";  //QQ 郵件伺服器      // 擷取系統屬性      Properties properties = System.getProperties();      // 設定郵件伺服器      properties.setProperty("mail.smtp.host", host);      properties.put("mail.smtp.auth", "true");      // 擷取預設session對象      Session session = Session.getDefaultInstance(properties,new Authenticator(){        public PasswordAuthentication getPasswordAuthentication()        {         return new PasswordAuthentication("xxx@qq.com", "qq郵箱密碼"); //寄件者郵件使用者名、密碼        }       });      try{         // 建立預設的 MimeMessage 對象         MimeMessage message = new MimeMessage(session);         // Set From: 頭部頭欄位         message.setFrom(new InternetAddress(from));         // Set To: 頭部頭欄位         message.addRecipient(Message.RecipientType.TO,                                  new InternetAddress(to));         // Set Subject: 頭部頭欄位         message.setSubject("This is the Subject Line!");         // 設定訊息體         message.setText("This is actual message");         // 發送訊息         Transport.send(message);         System.out.println("Sent message successfully....from cnblogs.com");      }catch (MessagingException mex) {         mex.printStackTrace();      }   }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.