亲宝软件园·资讯

展开

spring boot 发送邮件 SpringBoot添加Email发送功能及常见异常详解

loongshawn 人气:0
想了解SpringBoot添加Email发送功能及常见异常详解的相关内容吗,loongshawn在本文为您仔细讲解spring boot 发送邮件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring,boot,发送邮件,spring,boot,发邮件,spring,boot,邮件,下面大家一起来学习吧。

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,使得配置邮件发送不再复杂。

加载全部内容

相关教程
猜你喜欢
用户评论