您好,登錄后才能下訂單哦!
1、完整的郵件發送代碼
1.1、依賴包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-support</artifactId> <version>2.0.8</version> <exclusions> <exclusion> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
主要用到了兩個jar包:mail-1.4.7.jar、spring-support-2.0.8.jar.
1.2、郵件發送類
package com.autonavi.utils; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import com.autonavi.constants.Constant; public class EmailUtils { private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class); public static boolean sendHtmlMail(String subject,String content,String receiver){ boolean result = true; try{ JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); // 設定mail server senderImpl.setHost("smtp.abcdefg.com"); senderImpl.setPort(345); senderImpl.setUsername(Constant.email); // 根據自己的情況,設置發件郵箱地址 senderImpl.setPassword(Constant.email_password); // 根據自己的情況, 設置password senderImpl.setDefaultEncoding("UTF-8"); Properties prop = new Properties(); prop.put("mail.smtp.auth", "true"); // 將這個參數設為true,讓服務器進行認證,認證用戶名和密碼是否正確 prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); senderImpl.setJavaMailProperties(prop); // 建立郵件消息,發送簡單郵件和html郵件的區別 MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); // 設置收件人,寄件人 messageHelper.setTo(receiver); messageHelper.setFrom(Constant.email); messageHelper.setSubject(subject); // true 表示啟動HTML格式的郵件 messageHelper.setText(content,true); // 發送郵件 senderImpl.send(mailMessage); } catch (MessagingException e) { // TODO Auto-generated catch block result = false; logger.info("EmailUtils.method [sendHtmlMail]: email send result-" + result +",error message-" + e); } return result; } }
以上設置中,有幾個點需要注意:
第一點:
senderImpl.setUsername(Constant.email); senderImpl.setPassword(Constant.email_password);
上面兩個方法是用來設置發件的郵箱,郵箱地址要寫全,如aba@abc.com。
如果設置得不對,會提示權限錯誤。
第二點:
senderImpl.setDefaultEncoding(“UTF-8”);
這個一定記得設置,否則會郵件發出去會是下面這種結果。
第三點:
Properties prop = new Properties(); prop.put(“mail.smtp.auth”, “true”); prop.put(“mail.smtp.ssl.enable”, “true”); prop.put(“mail.smtp.socketFactory.class”, “javax.NET.ssl.SSLSocketFactory”); senderImpl.setJavaMailProperties(prop);
一定要記得配置Properties,且上述配置缺一不可,如果沒配置,大家會看見各種奇怪的異常。
1.3、郵件正文處理,使用HTML模版
下面的getHtmlStr()方法用來將待發送的內容處理為HTML模版。
public static String getHtmlStr(JSONArray data,String receiver,int day){ JSONObject json = data.getJSONObject(0); String title = json.getString("task_tittle"); // NO.1、獲取收件人名 String receiverName = getEmailStr(receiver); // NO.2、獲取郵件表格 String emailTable = getTableStr(data); // NO.3、獲取郵件時間 String emailDate = Date2Str.getCurrentDate2(); String html = "<html><head></head><body>" + "<p>" +receiverName+" 您好,</p>" + "<p> 生產日程-<font size=\"4\" color=\"#FF0000\" face=\"Verdana\" >"+title+"</font>中的下列任務將于<font size=\"4\" color=\"#FF0000\" face=\"Verdana\" >"+day+"</font>天后開始啟動,請關注:</p>" + "<div style=\"padding-left:20px\">" + "<table border=\"1px\" cellspacing=\"0px\" style=\"border-collapse:collapse\">" + "<tr>" + "<td>任務名</td><td>啟動時間</td><td>結束時間</td>" + "</tr>" + emailTable + "</table></div>" + "<p> 每項任務的詳細情況,請登陸 " + "<a href=\"http://100.78.205.244:8080\"><font size=\"4\" color=\"#FF0000\">項目綜合管理&評價系統</font></a> 查看!</p>" + "<p>項目綜合管理&評價系統</br>"+emailDate+"</p>" + "</body></html>"; return html; }
應用改模版后,發出的郵件顯示效果如下:
至于具體業務場景,你想定義什么樣的模版都行。
2、常見異常
503異常
2016-04-13-16-48 [scheduler-3] [org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler] [ERROR] - Unexpected error occurred in scheduled task. org.springframework.mail.MailSendException; nested exception details (1) are: Failed message 1: javax.mail.SendFailedException: Invalid Addresses; nested exception is: com.sun.mail.smtp.SMTPAddressFailedException: 503 RCPT account isn't a local account at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1862) at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1118) at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:388) at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:332) at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:328) at com.autonavi.utils.EmailUtils.sendHtmlMail(EmailUtils.java:50) at com.autonavi.method.gaokuai.IssueForward.action(IssueForward.java:81) at com.autonavi.task.ScheduledTasks.executeAutoAssignTask(ScheduledTasks.java:121) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 503 RCPT account isn't a local account at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1715) ... 21 more
如果運行過程中報上述異常,請再次核對收發郵件的郵箱賬號是否有效。
3、總結
SpringBoot郵件發送主要是利用已封裝好的兩個jar包:mail-1.4.7.jar、spring-support-2.0.8.jar,使得配置郵件發送不再復雜。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。