發送郵件的代碼是我從以前的一個應用上直接拷貝過來的。以前使用的騰訊的郵件服務,程式執行起來沒有任何問題。後來修改為微軟office365郵件服務後,卻遇到了兩個問題。
問題一,tls加密設定
異常資訊如下:
複製代碼 代碼如下:
Exception in thread "main" com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
這個解決起來比較容易。找了些資料,添加如下配置即可:
mail.smtp.starttls.enable = true
問題二,提示協議為null:
異常資訊如下:
Exception in thread "main" javax.mail.NoSuchProviderException: Invalid protocol: null
at javax.mail.Session.getProvider(Session.java:449)
at javax.mail.Session.getTransport(Session.java:667)
at javax.mail.Session.getTransport(Session.java:648)
at javax.mail.Session.getTransport(Session.java:634)
這個問題是在將應用部署到生產環境後才遇到的。經檢查後發現調用的jar包不是我在maven中指定的版本。後來確認是應用使用的jar包和容器(就是jetty)使用的jar包衝突了。容器使用的jar版本較舊,不過預設優先載入容器的jar。這樣問題解決思路有兩個:
- 依賴容器的jar重新寫代碼;
- 更新容器的jar。
第二個選擇多少有些危險,就採用第一個選項好了,只需要修改一行即可:
Transport transport = session.getTransport("smtp");
這個問題在javax.mail 1.4版本中會出現。之後較高的版本會預設採用SMTP協議發送郵件。
修改後的程式:
package com.zhyea.zytools; import java.util.Date;import java.util.Properties; import javax.mail.Message;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage; public class MailSender { private static final String MAIL_SMTP_HOST = "smtp.exmail.qq.com"; private static final Integer MAIL_SMTP_PORT = 587; private static final Boolean MAIL_SMTP_AUTH = true; private static final String MAIL_SMTP_USER = "robin@zhyea.com"; private static final String MAIL_SMTP_PASSWORD = "robinzhyea"; private static Properties props = new Properties(); static { props.put("mail.smtp.host", MAIL_SMTP_HOST); props.put("mail.smtp.auth", MAIL_SMTP_AUTH); props.put("mail.smtp.user", MAIL_SMTP_USER); props.put("mail.smtp.password", MAIL_SMTP_PASSWORD); props.put("mail.smtp.starttls.enable", true); } /** * 發送郵件 */ public static void send(String to, String title, String content) { try { Session session = Session.getInstance(props);//建立郵件會話 MimeMessage message = new MimeMessage(session);//由郵件會話建立一個訊息對象 message.setFrom(new InternetAddress(MAIL_SMTP_PASSWORD));//設定寄件者的地址 message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//設定收件者,並設定其接收類型為TO //設定信件內容 //message.setText(mailContent); //發送 純文字 郵件 TODO message.setSubject(title);//設定標題 message.setContent(content, "text/html;charset=gbk"); //發送HTML郵件,內容樣式比較豐富 message.setSentDate(new Date());//設定發信時間 message.saveChanges();//儲存郵件資訊 //發送郵件 Transport transport = session.getTransport("smtp"); transport.connect(MAIL_SMTP_USER, MAIL_SMTP_PASSWORD); transport.sendMessage(message, message.getAllRecipients());//發送郵件,其中第二個參數是所有已設好的收件者地址 transport.close(); } catch (Exception e) { e.printStackTrace(); } } }