1. 程式人生 > >分享一個郵件傳送的java例項(純文字,帶附件,多人抄送,多人密送)

分享一個郵件傳送的java例項(純文字,帶附件,多人抄送,多人密送)

貼程式碼:

  1 import javax.activation.DataHandler;
  2 import javax.activation.FileDataSource;
  3 import javax.mail.*;
  4 import javax.mail.internet.*;
  5 import java.util.Date;
  6 import java.util.Properties;
  7 import java.util.logging.Logger;
  8 
  9 /**
 10  * @author kabuqinuo
 11  * @date 2018/7/18 8:53
12 */ 13 /*傳送郵件工具類*/ 14 public class SendMailUtil { 15 16 private static Logger logger = Logger.getLogger(String.valueOf(SendMailUtil.class)); 17 18 19 //測試方法 20 public static void main(String[] args) throws Exception { 21 //boolean a = SendMailUtil.getContenet("18-4-25","上海")
22 String to = "[email protected]";//接收人 23 boolean a = SendMailUtil.sendMails("郵件的標題","傳送人",to,"(抄送人郵箱可多個可為空)","(密送人郵箱可多個可為空)",SendMailUtil.getContenet(),"(附件可為空)"); 24 System.out.println(a); 25 } 26 27 28 //獲取傳送的內容 29 public static String getContenet(){
30 String content = ""; 31 content = "要傳送的郵件內容"; 32 return content; 33 } 34 35 /* 36 * 設定傳送email的基本引數 37 * @param title 郵件標題 38 * @param personal 傳送人(郵箱上顯示的傳送人名稱) 39 * @param to 收件人郵箱 40 * @param copys 抄送人郵箱 41 * @param blind 密送人郵箱 42 * @param content 郵件內容 43 * @param file 附件 44 * @return 45 * @throws Exception 46 */ 47 public static boolean sendMails(String title, String personal,String to,String copys,String blind,String content,String file) { 48 Properties prop = new Properties(); 49 prop.setProperty("mail.host", "smtp.sina.com");// 設定伺服器地址 50 prop.setProperty("mail.transport.protocol", "smtp");// 郵件傳送協議 51 prop.setProperty("mail.smtp.auth", "true");// 是否要求身份認證 52 prop.setProperty("mail.smtp.port", "25"); // SMTP郵件伺服器預設埠 53 //使用JavaMail傳送郵件的5個步驟 54 //1、建立session 55 Session session = Session.getInstance(prop); 56 //開啟Session的debug模式,這樣就可以檢視到程式傳送Email的執行狀態 57 session.setDebug(true); 58 //2、通過session得到transport物件 59 Transport ts = null; 60 try { 61 ts = session.getTransport(); 62 //3、使用郵箱的使用者名稱和密碼連上郵件伺服器,傳送郵件時,發件人需要提交郵箱的使用者名稱和密碼給smtp伺服器,使用者名稱和密碼都通過驗證之後才能夠正常傳送郵件給收件人。 63 try { 64 ts.connect("smtp.sina.com", "[email protected]", "xxx");//傳送者的郵箱及密碼 65 } catch (MessagingException e) { 66 logger.info("連線郵件伺服器錯誤:"); 67 throw new AdminException(ResultEnum.CONNECTION_FAIL); 68 } 69 } catch (NoSuchProviderException e) { 70 logger.info("連線郵件伺服器錯誤:"); 71 throw new AdminException(ResultEnum.CONNECTION_FAIL); 72 } 73 //4、建立郵件 74 Message message; 75 try { 76 if (file == null || file.isEmpty()){ 77 message = createSimple(session, title, personal, to, copys, blind, content); 78 }else{ 79 message = createSimplees(session, title, personal, to, copys, blind, content,file); 80 } 81 //5、傳送郵件 82 ts.sendMessage(message, message.getAllRecipients()); 83 ts.close(); 84 return true; 85 }catch (Exception e){ 86 e.printStackTrace(); 87 } 88 return false; 89 } 90 91 /* 92 * 傳送郵件(純文字) 93 * @param session 94 * @param title 郵件標題 95 * @param personal 傳送人(郵箱上顯示的傳送人名稱) 96 * @param to 收件人郵箱 97 * @param copys 抄送人郵箱 98 * @param blind 密送人郵箱 99 * @param content 郵件內容 100 * @return 101 * @throws Exception 102 */ 103 private static MimeMessage createSimple(Session session,String title, String personal, String to, String copys, String blind, String content) throws Exception { 104 MimeMessage message = new MimeMessage(session); 105 //指明郵件的發件人 106 message.setFrom(new InternetAddress("[email protected]", personal, "UTF-8")); 107 //指明郵件的收件人,現在發件人和收件人是一樣的,那就是自己給自己發 108 InternetAddress[] tos = new InternetAddress().parse(to); 109 message.setRecipients(Message.RecipientType.TO,tos); 110 //預防一個無語的錯誤:554 DT:SPM 111 //message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse("[email protected]")); 112 //抄送 113 if (copys != null && !copys.isEmpty()){ 114 InternetAddress[] cc = new InternetAddress().parse(copys); 115 message.setRecipients(Message.RecipientType.CC,cc); 116 } 117 if (blind != null && blind.isEmpty()){ 118 InternetAddress[] bcc = new InternetAddress().parse(blind); 119 message.setRecipients(Message.RecipientType.BCC,bcc); 120 } 121 //設定傳送時間 122 message.setSentDate(new Date()); 123 //郵件的標題 124 message.setSubject(title); 125 //郵件的文字內容 126 message.setContent(content, "text/html;charset=UTF-8"); 127 // 儲存並生成最終的郵件內容 128 message.saveChanges(); 129 //返回建立好的郵件物件 130 return message; 131 } 132 133 /* 134 * 傳送郵件(帶附件) 135 * @param session 136 * @param title 郵件標題 137 * @param personal 傳送人(郵箱上顯示的傳送人名稱) 138 * @param to 收件人郵箱 139 * @param copys 抄送人郵箱 140 * @param blind 密送人郵箱 141 * @param content 郵件內容 142 * @param file 附件 143 * @return 144 * @throws Exception 145 */ 146 private static MimeMessage createSimplees(Session session,String title, String personal, String to, String copys, 147 String blind, String content,String file) throws Exception { 148 MimeMessage message = new MimeMessage(session); 149 //指明郵件的發件人 150 message.setFrom(new InternetAddress("[email protected]", personal, "UTF-8")); 151 //指明郵件的收件人,發件人和收件人是一樣的,那就是自己給自己發 152 InternetAddress[] tos = new InternetAddress().parse(to); 153 message.setRecipients(Message.RecipientType.TO,tos); 154 //抄送 155 if (copys != null && !copys.isEmpty()){ 156 InternetAddress[] cc = new InternetAddress().parse(copys); 157 message.setRecipients(Message.RecipientType.CC,cc); 158 } 159 if (blind != null && blind.isEmpty()){ 160 InternetAddress[] bcc = new InternetAddress().parse(blind); 161 message.setRecipients(Message.RecipientType.BCC,bcc); 162 } 163 //設定傳送時間 164 message.setSentDate(new Date()); 165 //郵件的標題 166 message.setSubject(title); 167 168 // 要求閱讀回執(收件人閱讀郵件時會提示回覆發件人,表明郵件已收到,並已閱讀) 169 message.setHeader("Disposition-Notification-To", "[email protected]"); 170 171 MimeBodyPart text = new MimeBodyPart(); 172 text.setContent(content, "text/html;charset=UTF-8"); 173 174 //建立郵件附件 175 MimeBodyPart attach = new MimeBodyPart(); 176 DataHandler dh = new DataHandler(new FileDataSource(file)); 177 attach.setDataHandler(dh); 178 attach.setFileName(MimeUtility.encodeWord(dh.getName())); 179 180 //建立容器描述資料關係 181 MimeMultipart mp = new MimeMultipart(); 182 mp.addBodyPart(text); 183 mp.addBodyPart(attach); 184 mp.setSubType("mixed"); 185 186 message.setContent(mp); 187 message.saveChanges(); 188 189 190 //返回建立好的郵件物件 191 return message; 192 } 193 }

以上是一個郵件傳送的例項,可以純文字傳送郵件 也可以帶著附件傳送,至於帶圖片的 還沒有寫。

用以上例項本人之前用於企業傳送郵件,所以傳送者的郵箱可密碼是寫死的,在64行,如果想自由定義傳送人的郵箱和密碼,可將其上程式碼稍微改改,把傳送者的郵箱和密碼引數提取出來。

以上程式碼中的某些命名和專案中的某些欄位衝突 所以稍微改了改。

如果直接拿以上程式碼來用,會缺少一個異常處理類,這個異常處理類就是專案的整個異常處理工具,簡單來說就是丟擲錯誤提示。其他沒什麼問題,本人親測。