SpringBoot添加Email发送功能及常见异常详解

时间:2021-09-05 04:45:08

1、完整的邮件发送代码

1.1、依赖包

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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、邮件发送类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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;
  }
 
}

以上设置中,有几个点需要注意:

第一点:

?
1
2
senderImpl.setUsername(Constant.email);
senderImpl.setPassword(Constant.email_password);

上面两个方法是用来设置发件的邮箱,邮箱地址要写全,如aba@abc.com。

如果设置得不对,会提示权限错误。

第二点:

?
1
senderImpl.setDefaultEncoding(“UTF-8”);

这个一定记得设置,否则会邮件发出去会是下面这种结果。

SpringBoot添加Email发送功能及常见异常详解

第三点:

?
1
2
3
4
5
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模版。

  1. public static String getHtmlStr(JSONArray data,String receiver,int day){ 
  2.  
  3.     JSONObject json = data.getJSONObject(0); 
  4.     String title = json.getString("task_tittle"); 
  5.     // NO.1、获取收件人名 
  6.     String receiverName = getEmailStr(receiver); 
  7.     // NO.2、获取邮件表格 
  8.     String emailTable = getTableStr(data); 
  9.     // NO.3、获取邮件时间 
  10.     String emailDate = Date2Str.getCurrentDate2(); 
  11.  
  12.     String html = "<html><head></head><body>" 
  13.           + "<p>" +receiverName+" 您好,</p>" 
  14.           + "<p>&nbsp;&nbsp;&nbsp;&nbsp;生产日程-<font size="4" color="#FF0000" face="Verdana" >"+title+"</font>中的下列任务将于<font size="4" color="#FF0000" face="Verdana" >"+day+"</font>天后开始启动,请关注:</p>" 
  15.           + "<div style="padding-left:20px">" 
  16.           + "<table border="1px" cellspacing="0px" style="border-collapse:collapse">" 
  17.           + "<tr>" 
  18.           + "<td>任务名</td><td>启动时间</td><td>结束时间</td>" 
  19.           + "</tr>" 
  20.           + emailTable 
  21.           + "</table></div>" 
  22.           + "<p>&nbsp;&nbsp;&nbsp;&nbsp;每项任务的详细情况,请登陆 " 
  23.           + "<a href="http://100.78.205.244:8080"><font size="4" color="#FF0000">项目综合管理&评价系统</font></a> 查看!</p>" 
  24.           + "<p>项目综合管理&评价系统</br>"+emailDate+"</p>" 
  25.           + "</body></html>"
  26.  
  27.     return html; 
  28.   } 
 

应用改模版后,发出的邮件显示效果如下:

SpringBoot添加Email发送功能及常见异常详解

至于具体业务场景,你想定义什么样的模版都行。

2、常见异常

503异常

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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,使得配置邮件发送不再复杂。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/loongshawn/article/details/51036490