SpringBoot添加Email发送功能及常见异常详解
程序员文章站
2024-02-28 18:32:40
1、完整的邮件发送代码
1.1、依赖包
org.springframework...
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,使得配置邮件发送不再复杂。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。