2012年9月4日 星期二

[ Java 代碼範本 ] 透過 Yahoo Mail account 使用 JavaMail 送信

Preface : 
最近需要寫一個 watch dog 來定時檢視我們提供的 service 是否還活著, 由於需要再 service break 發 mail 通知相關人等, 故拜了 Google 大神將實作細節整理在這. 
這邊使用 Yahoo SMTP/POP 作為 mail sending 的平台, 因此你需要有對應的 Yahoo Mail account; 另外使用的 Java 套件是 JavaMail, 你需要將它加到你專案的 classpath 中. 

Mail account 設定 : 
在開使撰寫代碼前, 先要設定你的 Mail Account. 請進入你的 Mail account 後, 在左上方按照下面指示進入設定頁面 : 
 

接著按照下面說明完成設定 : 
 

範例代碼 : 
接著我建立的一個類別 MailAgent 方便後續使用, 完整代碼如下 : 
- MailAgent.java : 
  1. package test;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.List;  
  5. import java.util.Properties;  
  6.   
  7. import javax.mail.Authenticator;  
  8. import javax.mail.Message;  
  9. import javax.mail.PasswordAuthentication;  
  10. import javax.mail.Session;  
  11. import javax.mail.Store;  
  12. import javax.mail.Transport;  
  13. import javax.mail.internet.InternetAddress;  
  14. import javax.mail.internet.MimeMessage;  
  15.   
  16. import org.apache.commons.codec.binary.Base64;  
  17.   
  18. public class MailAgent {  
  19.     private String          username = "";  // Your account in Yahoo  
  20.     private String          password = "";  // Your password of account in Yahoo  
  21.     private String          smtpHost = "smtp.mail.yahoo.com";  
  22.     private String          popHost = "pop.mail.yahoo.com";  
  23.     private String          fromAddress = "";  
  24.     private List  toAddressList = null;  
  25.     private Properties      props = null;  
  26.     public boolean          isDebug = false;  
  27.   
  28.     public MailAgent(){}  
  29.     public MailAgent(String user,String pwd, String smtpHost, String popHost)  
  30.     {  
  31.         this.username = user;   
  32.         this.password = pwd;  
  33.         this.smtpHost = smtpHost;  
  34.         this.popHost = popHost;  
  35.     }  
  36.       
  37.     public void resetProp()  
  38.     {  
  39.         props = System.getProperties();       
  40.         props.put("mail.smtp.host", smtpHost);  
  41.         //props.put("mail.from",from);  
  42.         props.put("mail.smtp.starttls.enable""true");  
  43.         props.put("mail.smtp.auth""true");  
  44.         props.put("mail.debug", String.valueOf(isDebug));  
  45.     }  
  46.       
  47.     public String getUsername() {  
  48.         return username;  
  49.     }  
  50.     public void setUsername(String username) {  
  51.         this.username = username;  
  52.     }  
  53.     public String getPassword() {  
  54.         return password;  
  55.     }  
  56.     public void setPassword(String password)   
  57.     {  
  58.         this.password = password;  
  59.     }  
  60.     public void setPasswordInBase64(String passwordInBase64)  
  61.     {  
  62.         Base64 base64 = new Base64();  
  63.         this.password = new String(base64.decode(passwordInBase64.getBytes()));  
  64.     }  
  65.       
  66.     public List getToAddressList() {  
  67.         return toAddressList;  
  68.     }  
  69.     public void setToAddressList(List toAddressList) {  
  70.         this.toAddressList = toAddressList;  
  71.     }  
  72.     public String getSmtpHost() {  
  73.         return smtpHost;  
  74.     }  
  75.     public void setSmtpHost(String smtpHost) {  
  76.         this.smtpHost = smtpHost;  
  77.     }  
  78.     public String getPopHost() {  
  79.         return popHost;  
  80.     }  
  81.     public void setPopHost(String popHost) {  
  82.         this.popHost = popHost;  
  83.     }  
  84.       
  85.     public String getFromAddress() {  
  86.         return fromAddress;  
  87.     }  
  88.     public void setFromAddress(String fromAddress) {  
  89.         this.fromAddress = fromAddress;  
  90.     }  
  91.     public boolean isDebug() {  
  92.         return isDebug;  
  93.     }  
  94.     public void setDebug(boolean isDebug) {  
  95.         this.isDebug = isDebug;  
  96.     }  
  97.     public boolean sendMail(List toAddressList, String subject, String body)  
  98.     {  
  99.         try  
  100.         {  
  101.             if(props==null) resetProp();  
  102.             // Get session  
  103.             Session session = Session.getDefaultInstance(props, new Authenticator() {  
  104.                 @Override  
  105.                 protected PasswordAuthentication getPasswordAuthentication() {  
  106.                     return new PasswordAuthentication(username, password);  
  107.                 }  
  108.             });  
  109.             session.setDebug(isDebug);  
  110.             // Pop Authenticate yourself  
  111.             Store store = session.getStore("pop3");  
  112.             store.connect(popHost, username, password);  
  113.               
  114.             MimeMessage message = new MimeMessage(session);  
  115.             message.setFrom(new InternetAddress(fromAddress));  
  116.             message.setSubject(subject);  
  117.             message.setText(body);        
  118.             for(String to:toAddressList)  
  119.             {                                 
  120.                 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));                                         
  121.             }     
  122.             // Send message  
  123.             Transport.send(message);  
  124.             return true;  
  125.         }  
  126.         catch(Exception e)  
  127.         {  
  128.             e.printStackTrace();  
  129.         }  
  130.         return false;  
  131.     }  
  132.       
  133.     public boolean sendMail(String toAddress, String subject, String body)  
  134.     {  
  135.         List toAddressList = new LinkedList();  
  136.         toAddressList.add(toAddress);  
  137.         return this.sendMail(toAddressList, subject, body);  
  138.     }  
  139.       
  140.     public boolean sendMail(String subject, String body)  
  141.     {  
  142.         if(toAddressList==null || fromAddress==null || fromAddress.trim().isEmpty()) return false;  
  143.         else  
  144.         {  
  145.             return sendMail(toAddressList, subject, body);  
  146.         }  
  147.     }  
  148. }  
接著你只要創建這個類別的物件, 設定你的 account 訊息與使用的 mail address (From address of mail), 便可以透過 API sendMail() 發送郵件. 簡單使用範例如下 : 
  1. public static void main(String[] args) {  
  2.     MailAgent mailAgent = new MailAgent();  
  3.     mailAgent.setUsername("your yahoo account");  
  4.     mailAgent.setPassword("password of your account");  
  5.     mailAgent.setFromAddress("from address of your mail");  
  6.     List toAddressList = new LinkedList();  
  7.     toAddressList.add("johnlee@ntnu.edu.tw"); // Add to-address1 of mail  
  8.     toAddressList.add("puremonkey2007@gmail.com"); // Add to-address2 of mail  
  9.     mailAgent.sendMail(toAddressList, "Hello Test""This is for testing");  
  10. }  
接著去你發送的信箱應該就可以看到上面代碼發送的測試 mail, 下面是我的 gmail 信箱收到的結果 : 
 

Supplement : 
How do I use the Yahoo SMTP server to send mail with the JavaMail API? 
TLS issue when sending to gmail through JavaMail

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...