【乾貨】使用Java發送各種格式的郵件

原文鏈接


          測試可用:

         有些重複代碼沒有給註釋。類的方法作用自行查看API瞭解,最後附上源碼。


        首先使用JavaMail的jar,官網可下載。

       公共靜態的常量:

       

[java] view plain copy
  1. public final static String MAIL = "@sina.com"// 郵箱格式  
  2. public final static String SEND_HOST = "smtp.sina.com"// 郵箱發送服務器  
  3. public final static String ACCEPT_HOST = "pop.sina.com"// 郵箱服務器  
  4. public final static String SEND_USER = "xxxx"// 用戶名  
  5. public final static String SEND_PWD = "xxxxx"// 密碼  
  6. public final static String FROM_MAIL = SEND_USER + "@sina.com";// 發送方郵箱地址  
  7. public final static String TO_MAIL = "[email protected]"// 接收方郵箱地址  
  8. public final static String CC_MAIL = SEND_USER + MAIL; // 抄送方郵箱地址  
  9. public final static String BCC_MAIl = SEND_USER + MAIL; // 密送方郵箱地址  
  10.   
  11. public final static String ENCODE = "UTF-8";  
  12. public static Date date = new Date();  
    

        使用Java自帶的接口和類發送文本格式郵件

   

[java] view plain copy
  1.  Properties prop = new Properties();  
  2.         prop.setProperty("mail.host", SEND_HOST);  
  3.         prop.setProperty("mail.transport.protocol""smtp");  
  4.         prop.setProperty("mail.smtps.ssl.enable""true");  
  5. //      prop.setProperty("mail.smtp.port", "25");  
  6.         prop.setProperty("mail.smtp.auth""true");  
  7.           
  8.        Session session = Session.getInstance(prop);  //創建應用會話  
  9.          
  10.        Message message = new MimeMessage(session);   //消息摘要,是郵件的主體  
  11.        message.setSubject("測試");       //設置主題  
  12.        message.setText("你好!");    //郵件內容  
  13.        message.setSentDate(new Date());  //發送日期  
  14.        message.setFrom(new InternetAddress(FROM_MAIL)); //發送方  
  15.        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_MAIL)); //接受方  
  16.        message.saveChanges();  //保存郵件主體對象內容  
  17.          
  18.        Transport transport = session.getTransport();    //傳輸對象  
  19.        transport.connect(SEND_HOST, FROM_MAIL, SEND_PWD);  //連接服務器中的郵箱  
  20.        transport.sendMessage(message, message.getAllRecipients());  //發送  
  21.        transport.close();  //關閉傳輸  
  22.        System.out.println("Successfully  send mail to all user");  

感覺自帶的接口方法比較麻煩,使用spring封裝的javamail,記的導入spring相關包。


使用spring發送文本格式的郵件,代碼如下:

[java] view plain copy
  1. public  static void sendTxtMail() throws MailException {  
  2.         JavaMailSenderImpl send = new JavaMailSenderImpl();  
  3.            Properties prop = new Properties();  
  4.            prop.setProperty("mail.transport.protocol""smtp");  
  5.            prop.setProperty("mail.host", SEND_HOST);     
  6.   
  7.             prop.setProperty("mail.smtps.ssl.enable""true");  
  8.             prop.setProperty("mail.smtp.auth""true");  
  9.   
  10.               
  11.           send.setUsername(SEND_USER);  
  12.           send.setPassword(SEND_PWD);  
  13.              send.setJavaMailProperties(prop);     
  14.             
  15.           SimpleMailMessage  msg = new SimpleMailMessage();  
  16.           msg.setFrom(FROM_MAIL);  
  17.           msg.setTo(TO_MAIL);  
  18.           msg.setReplyTo(FROM_MAIL);  
  19.           msg.setCc(CC_MAIL);  
  20.           msg.setBcc(BCC_MAIl);  
  21.           msg.setSentDate(date);  
  22.           msg.setSubject("發送的文本格式郵件");  
  23.           msg.setText("文本格式 測試成功!");  
  24.           send.send(msg);  
  25.           System.out.println("Successfully  send mail to the user");  

使用spring的封裝方法發送Html格式郵件 ,代碼如下:

[java] view plain copy
  1. // 發送Html格式郵件  
  2. public static void sendHtmlMail() throws Exception {  
  3.     JavaMailSenderImpl send = new JavaMailSenderImpl();  
  4.     Properties prop = new Properties();  
  5.     prop.setProperty("mail.transport.protocol""smtp");  
  6.     prop.setProperty("mail.host", SEND_HOST);  
  7.     prop.setProperty("mail.smtps.ssl.enable""true");  
  8.     prop.setProperty("mail.smtp.auth""true");  
  9.   
  10.     send.setUsername(SEND_USER);  
  11.     send.setPassword(SEND_PWD);  
  12.     send.setJavaMailProperties(prop);  
  13.   
  14.     MimeMessage msg = send.createMimeMessage();  
  15.   
  16.     MimeMessageHelper helper = new MimeMessageHelper(msg, ENCODE);  
  17.     helper.setFrom(FROM_MAIL);  
  18.     helper.setTo(TO_MAIL);  
  19.     helper.setReplyTo(FROM_MAIL);  
  20.     helper.setCc(CC_MAIL);  
  21.     helper.setBcc(BCC_MAIl);  
  22.     helper.setSentDate(date);  
  23.     helper.setSubject("發送的HTML格式郵件");  
  24.     String html = "<font size='5' color='red'>HTML格式測試成功!</font>";  
  25.     helper.setText(html, true); // 郵件內容,參數true表示是html代碼  
  26.     send.send(msg);  
  27.     System.out.println("Successfully  send mail to the user");  


使用spring的封裝方法發送帶內嵌內容的Html格式郵件 ,代碼如下:


[java] view plain copy
  1. // 發送帶內嵌文件的HTML格式郵件  
  2.     public static void sendInlineMail() throws Exception {  
  3.         // spring提供的郵件實現類  
  4.         JavaMailSenderImpl send = new JavaMailSenderImpl();  
  5.         Properties prop = new Properties();  
  6.         prop.setProperty("mail.transport.protocol""smtp"); // 設置郵件發送協議  
  7.         prop.setProperty("mail.host", SEND_HOST); // 郵件服務器地址  
  8.         prop.setProperty("mail.smtps.ssl.enable""true"); // 郵件ssl驗證  
  9.         prop.setProperty("mail.smtp.auth""true"); // 郵件服務身份驗證  
  10.   
  11.         send.setUsername(SEND_USER); // 設置用戶名  
  12.         send.setPassword(SEND_PWD); // 設置密碼  
  13.         send.setJavaMailProperties(prop);  
  14.   
  15.         MimeMessage msg = send.createMimeMessage();  
  16.         // 指定HTML編碼,參數true表示爲multipart  
  17.         MimeMessageHelper helper = new MimeMessageHelper(msg, true, ENCODE);  
  18.         helper.setFrom(FROM_MAIL); // 發送者郵箱  
  19.         helper.setTo(TO_MAIL); // 接收者郵箱  
  20.         helper.setReplyTo(FROM_MAIL); // 回覆郵箱  
  21.         helper.setCc(CC_MAIL); // 抄送郵箱  
  22.         helper.setBcc(BCC_MAIl); // 密送郵箱  
  23.         helper.setSentDate(date); // 發送日期  
  24.         helper.setSubject("發送的帶有內部文件的HTML格式郵件");  
  25.         String html = "<font size='5' color='red'>HTML格式測試成功!</font>"  
  26.                 + "<img src ='cid:demoimg'>"// cid是一個固定前綴,demoimg是一個資源名稱  
  27.         helper.setText(html, true); // 郵件內容,參數true表示是html代碼  
  28.         ClassPathResource resource = new ClassPathResource("col.jpg"); // 加載項目路徑下資源  
  29.         helper.addInline("demoimg", resource); // 將資源綁定到demoimg上  
  30.         send.send(msg); // 發送郵件  
  31.         System.out.println("Successfully  send mail to the user");  
  32.     }  

使用spring的封裝方法發送帶附件的郵件 ,代碼如下:


[java] view plain copy
  1. // 發送帶附件的郵件  
  2.     public static void sendAttachmentMail() throws Exception {  
  3.         // spring提供的郵件實現類  
  4.         JavaMailSenderImpl send = new JavaMailSenderImpl();  
  5.         Properties prop = new Properties();  
  6.         prop.setProperty("mail.transport.protocol""smtp"); // 設置郵件發送協議  
  7.         prop.setProperty("mail.host", SEND_HOST); // 郵件服務器地址  
  8.         prop.setProperty("mail.smtps.ssl.enable""true"); // 郵件ssl驗證  
  9.         prop.setProperty("mail.smtp.auth""true"); // 郵件服務身份驗證  
  10.   
  11.         send.setUsername(SEND_USER); // 設置用戶名  
  12.         send.setPassword(SEND_PWD); // 設置密碼  
  13.         send.setJavaMailProperties(prop);  
  14.   
  15.         MimeMessage msg = send.createMimeMessage();  
  16.         // 指定HTML編碼,參數true表示爲multipart  
  17.         MimeMessageHelper helper = new MimeMessageHelper(msg, true, ENCODE);  
  18.         helper.setFrom(FROM_MAIL); // 發送者郵箱  
  19.         helper.setTo(TO_MAIL); // 接收者郵箱  
  20.         helper.setReplyTo(FROM_MAIL); // 回覆郵箱  
  21.         helper.setCc(CC_MAIL); // 抄送郵箱  
  22.         helper.setBcc(BCC_MAIl); // 密送郵箱  
  23.         helper.setSentDate(date); // 發送日期  
  24.         helper.setSubject("發送帶有附件的郵件");  
  25.         String html = "<font size='5' color='red'>附件測試成功!</font>";  
  26.         helper.setText(html, true); // 郵件內容,參數true表示是html代碼  
  27.         String demo = "demo.docx";  
  28.         ClassPathResource resource = new ClassPathResource(demo); // 加載項目路徑下資源  
  29.         helper.addAttachment(MimeUtility.encodeWord(demo), resource); // 如果文件是中文名,需要轉碼。  
  30.         send.send(msg); // 發送郵件  
  31.         System.out.println("Successfully  send mail to the user");  
  32.     }  


  

   在測試之前記得將郵箱smtp、pop設置上,否者會報驗證錯誤或連接服務錯誤 即50X系列錯誤。

 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章