Javamail實現郵件發送

  1. /* 
  2.  * 郵件發送類 
  3.  */  
  4. public class MailSenderUtil{  
  5.       
  6.   /** 
  7.   * 以HTML格式發送郵件,可帶附件,本方法可作爲對外接口提供。 
  8.   * @param mailInfo 待發送的郵件信息  
  9.  * @throws MessagingException  
  10.  * @throws AddressException  
  11.  * @throws UnsupportedEncodingException  
  12.   */    
  13.     public static void sendHtmlMailWithLocalAttach(MailSenderInfo mailInfo) throws AddressException, MessagingException, UnsupportedEncodingException {  
  14.           
  15.         // 判斷是否需要身份認證  
  16.         MyAuthenticator authenticator = null;  
  17.           
  18.         // 如果需要身份認證,則創建一個密碼驗證器  
  19.         if (mailInfo.isValidate()) {  
  20.             authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());  
  21.         }  
  22.         // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session  
  23.         Properties pro = mailInfo.getProperties();  
  24.         Session sendMailSession = Session.getDefaultInstance(pro, authenticator);  
  25.   
  26.         // 根據session創建一個郵件消息  
  27.         Message mailMessage = new MimeMessage(sendMailSession);  
  28.           
  29.         // 設置發送人  
  30.         mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));  
  31.           
  32.         // 設置收件人  
  33.         String[] toAddress = mailInfo.getToAddress();  
  34.         if(toAddress == null || toAddress.length < 1){  
  35.             throw new RuntimeException("收件人不得爲空!");  
  36.         }  
  37.         for (int i = 0; i < toAddress.length; i++) {  
  38.             mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress[i]));  
  39.         }  
  40.   
  41.         //設置抄送人  
  42.         String[] ccAddress = mailInfo.getCcAddress();  
  43.         if(ccAddress != null && ccAddress.length > 0){  
  44.             for (int i = 0; i < ccAddress.length; i++) {  
  45.                 mailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(ccAddress[i]));  
  46.             }  
  47.         }  
  48.           
  49.         // 設置郵件消息的主題  
  50.         mailMessage.setSubject(mailInfo.getTitle());  
  51.         // 設置郵件消息發送的時間  
  52.         mailMessage.setSentDate(new Date());  
  53.         // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象  
  54.         Multipart mainPart = new MimeMultipart();  
  55.         // 創建一個包含HTML內容的MimeBodyPart  
  56.         BodyPart html = new MimeBodyPart();  
  57.         // 設置HTML內容  
  58.         html.setContent(mailInfo.getContent(), "text/html; charset=GBK");  
  59.         mainPart.addBodyPart(html);  
  60.   
  61.         // 添加附件  
  62.         addAttachment(mailInfo, mainPart);  
  63.           
  64.         // 將MiniMultipart對象設置爲郵件內容  
  65.         mailMessage.setContent(mainPart);  
  66.   
  67.         // 發送郵件  
  68.         Transport.send(mailMessage);  
  69.     }   
  70.       
  71.     /* 
  72.      * 添加郵件附件,用本地的文件作爲附件 
  73.      */  
  74.     private static void addAttachment(MailSenderInfo mailInfo,Multipart mainPart) throws MessagingException, UnsupportedEncodingException{  
  75.              
  76.            String[] attachFileNames = mailInfo.getAttachFileNames();  
  77.            if(attachFileNames != null && attachFileNames.length > 0){  
  78.             for (int i = 0; i < attachFileNames.length; i++) {  
  79.                 MimeBodyPart mdp = new MimeBodyPart();  
  80.   
  81.                 // FileDataSource/DataHandler 會用到  
  82.                 // activation-1.1.jar,jdk6中已經包含了該jar中內容,不再需要單獨下載  
  83.                 // activation-1.1.jar  
  84.                 FileDataSource fds = new FileDataSource(attachFileNames[i]);  
  85.                 DataHandler dh = new DataHandler(fds);  
  86.                 mdp.setDataHandler(dh);  
  87.   
  88.                 // 保持附件名稱與原文件名稱一致的寫法,MimeUtility.encodeText()可以解決中文附件亂碼。  
  89.                 mdp.setFileName(MimeUtility.encodeText(fds.getName()));  
  90.                 mainPart.addBodyPart(mdp);  
  91.             }  
  92.            }  
  93.     }  
  94. }   
  95. /** 
  96.  * MyAuthenticator bean 
  97.  */  
  98. class MyAuthenticator extends Authenticator{   
  99.       String userName=null;   
  100.       String password=null;   
  101.           
  102.       public MyAuthenticator(){   
  103.       }   
  104.       public MyAuthenticator(String username, String password) {    
  105.         this.userName = username;    
  106.         this.password = password;    
  107.       }    
  108.       protected PasswordAuthentication getPasswordAuthentication(){   
  109.         return new PasswordAuthentication(userName, password);   
  110.       }   
  111.     }   
  112. /** 
  113.  * MailSenderInfo bean 
  114.  */  
  115. class MailSenderInfo {  
  116.     // 發送郵件的服務器的IP和端口  
  117.     private String mailServerHost;  
  118.     private String mailServerPort;;  
  119.     // 郵件發送者的地址  
  120.     private String fromAddress;  
  121.     //接收人地址  
  122.     private String[] toAddress;  
  123.     //抄送人地址  
  124.     private String[] ccAddress;  
  125.     // 登陸郵件發送服務器的用戶名和密碼  
  126.     private String userName;  
  127.     private String password;  
  128.       
  129.     // 是否需要身份驗證  
  130.     private boolean validate = false;  
  131.     // 郵件主題  
  132.     private String title;  
  133.     // 郵件的文本內容  
  134.     private String content;  
  135.       
  136.     // 郵件附件的文件名,含磁盤物理路徑,如D:\\Desktop\\index.html  
  137.     private String[] attachFileNames;  
  138.   
  139.     /** 
  140.      *  獲得郵件會話屬性  
  141.      * @return Properties 
  142.      */  
  143.     public Properties getProperties() {  
  144.         Properties p = new Properties();  
  145.         p.put("mail.smtp.host"this.mailServerHost);  
  146.         p.put("mail.smtp.port"this.mailServerPort);  
  147.         p.put("mail.smtp.auth", validate ? "true" : "false");  
  148.         return p;  
  149.     }  
  150.   
  151.     public String[] getCcAddress() {  
  152.         return ccAddress;  
  153.     }  
  154.   
  155.     public void setCcAddress(String[] ccAddress) {  
  156.         this.ccAddress = ccAddress;  
  157.     }  
  158.   
  159.     public String getMailServerHost() {  
  160.         return mailServerHost;  
  161.     }  
  162.   
  163.     public void setMailServerHost(String mailServerHost) {  
  164.         this.mailServerHost = mailServerHost;  
  165.     }  
  166.   
  167.     public String getMailServerPort() {  
  168.         return mailServerPort;  
  169.     }  
  170.   
  171.     public void setMailServerPort(String mailServerPort) {  
  172.         this.mailServerPort = mailServerPort;  
  173.     }  
  174.   
  175.     public boolean isValidate() {  
  176.         return validate;  
  177.     }  
  178.   
  179.     public void setValidate(boolean validate) {  
  180.         this.validate = validate;  
  181.     }  
  182.   
  183.     public String[] getAttachFileNames() {  
  184.         return attachFileNames;  
  185.     }  
  186.   
  187.     public void setAttachFileNames(String[] fileNames) {  
  188.         this.attachFileNames = fileNames;  
  189.     }  
  190.   
  191.     public String getFromAddress() {  
  192.         return fromAddress;  
  193.     }  
  194.   
  195.     public void setFromAddress(String fromAddress) {  
  196.         this.fromAddress = fromAddress;  
  197.     }  
  198.   
  199.     public String getPassword() {  
  200.         return password;  
  201.     }  
  202.   
  203.     public void setPassword(String password) {  
  204.         this.password = password;  
  205.     }  
  206.   
  207.     public String[] getToAddress() {  
  208.         return toAddress;  
  209.     }  
  210.   
  211.     public void setToAddress(String[] toAddress) {  
  212.         this.toAddress = toAddress;  
  213.     }  
  214.   
  215.     public String getUserName() {  
  216.         return userName;  
  217.     }  
  218.   
  219.     public void setUserName(String userName) {  
  220.         this.userName = userName;  
  221.     }  
  222.   
  223.     public String getTitle() {  
  224.         return title;  
  225.     }  
  226.   
  227.     public void setTitle(String title) {  
  228.         this.title = title;  
  229.     }  
  230.   
  231.     public String getContent() {  
  232.         return content;  
  233.     }  
  234.   
  235.     public void setContent(String textContent) {  
  236.         this.content = textContent;  
  237.     }  
  238. }  

 

使用

 

Java代碼  收藏代碼
  1. public static void main(String[] args) throws AddressException, UnsupportedEncodingException, MessagingException {  
  2.   
  3.         MailSenderInfo mail = new MailSenderInfo();  
  4.           
  5.         //設置附件  
  6.         mail.setAttachFileNames(new String[]{  
  7.                 "D:\\Desktop\\首頁.jpg",  
  8.                 "D:\\Desktop\\測試賬戶.java"  
  9.         });  
  10.         //設置抄送人  
  11.         mail.setCcAddress(new String[]{"[email protected]","[email protected]"});  
  12.         //設置正文  
  13.         mail.setContent("<h3>http://www.baidu.com</h3>");  
  14.         //設置發件郵箱  
  15.         mail.setFromAddress("[email protected]");  
  16.         //設置發件郵箱密碼  
  17.         mail.setPassword("123456");  
  18.         //設置郵件服務器  
  19.         mail.setMailServerHost("mail.XX.com");  
  20.         mail.setMailServerPort("25");  
  21.         //設置郵件主題  
  22.         mail.setTitle("我是主題");  
  23.         //設置收件人  
  24.         mail.setToAddress(new String[]{"[email protected]"});  
  25.         //設置用戶名  
  26.         mail.setUserName("33");  
  27.         mail.setValidate(true);  
  28.         MailSenderUtil.sendHtmlMailWithLocalAttach(mail);  
  29.     }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章