主要是看一下Springboot中发送邮件的方法,至于拦截Springboot全局异常之前的文章中有。

一 发送邮件

在Springboot中发送邮件非常简单。

pom.xml引入maven依赖

     <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>

在application.yml里设置发信人的账号、密码

spring:mail:host: smtp.qq.comusername: 27255XXXX@qq.compassword: njcvcbdkrofgbhieproperties:mail:smtp:auth: truestarttls:enable: truerequired: true

这个username就是未来发信时的邮箱地址,password是授权码。

这里以普通qq邮箱为例,注意password不是qq密码,而是授权码。

在qq邮箱-设置-账户,找到图片中的地方,开启IMAP/SMTP服务,开启后才能在别的客户端使用该qq邮箱发邮件,然后生成授权码,填写到application.yml的password位置。

然后就可以使用该邮箱作为发件人了。

看一下发邮件的具体代码,参考http://blog.csdn.net/clementad/article/details/51833416

package com.tianyalei.testmail.service;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;@Service
public class MailService {private final Logger logger = LoggerFactory.getLogger(this.getClass());@Autowiredprivate JavaMailSender sender;@Value("${spring.mail.username}")private String from;/*** 发送纯文本的简单邮件* @param to* @param subject* @param content*/public void sendSimpleMail(String to, String subject, String content){SimpleMailMessage message = new SimpleMailMessage();message.setFrom(from);message.setTo(to);message.setSubject(subject);message.setText(content);try {sender.send(message);logger.info("简单邮件已经发送。");} catch (Exception e) {logger.error("发送简单邮件时发生异常!", e);}}/*** 发送html格式的邮件* @param to* @param subject* @param content*/public void sendHtmlMail(String to, String subject, String content){MimeMessage message = sender.createMimeMessage();try {//true表示需要创建一个multipart messageMimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(from);helper.setTo(to);helper.setSubject(subject);helper.setText(content, true);sender.send(message);logger.info("html邮件已经发送。");} catch (MessagingException e) {logger.error("发送html邮件时发生异常!", e);}}/*** 发送带附件的邮件* @param to* @param subject* @param content* @param filePath*/public void sendAttachmentsMail(String to, String subject, String content, String filePath){MimeMessage message = sender.createMimeMessage();try {//true表示需要创建一个multipart messageMimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(from);helper.setTo(to);helper.setSubject(subject);helper.setText(content, true);FileSystemResource file = new FileSystemResource(new File(filePath));String fileName = filePath.substring(filePath.lastIndexOf(File.separator));helper.addAttachment(fileName, file);sender.send(message);logger.info("带附件的邮件已经发送。");} catch (MessagingException e) {logger.error("发送带附件的邮件时发生异常!", e);}}/*** 发送嵌入静态资源(一般是图片)的邮件* @param to* @param subject* @param content 邮件内容,需要包括一个静态资源的id,比如:<img src=\"cid:rscId01\" >* @param rscPath 静态资源路径和文件名* @param rscId 静态资源id*/public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){MimeMessage message = sender.createMimeMessage();try {//true表示需要创建一个multipart messageMimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(from);helper.setTo(to);helper.setSubject(subject);helper.setText(content, true);FileSystemResource res = new FileSystemResource(new File(rscPath));helper.addInline(rscId, res);sender.send(message);logger.info("嵌入静态资源的邮件已经发送。");} catch (MessagingException e) {logger.error("发送嵌入静态资源的邮件时发生异常!", e);}}
}

然后就可以使用里面的方法发邮件了。

可以先写个简单的测试类,调用

mailService.sendSimpleMail("wuweifeng@XXX.com", "主题:简单邮件", "测试邮件内容");

填写个收信人的地址就OK了。然后就能收到邮件了。收信人可以有多个,通过SimpleMailMessage可以看到。

二 拦截全局异常并发邮件

定义一个全局拦截类
package com.tianyalei.testmail.global;import com.tianyalei.testmail.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;import static org.springframework.http.HttpStatus.NOT_EXTENDED;/*** Created by wuwf on 17/3/31.* 全局异常处理*/
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {private Logger logger = LoggerFactory.getLogger(getClass().getName());@Autowiredprivate MailService mailService;/*** 在controller里面内容执行之前,校验一些参数不匹配啊,Get post方法不对啊之类的*/@Overrideprotected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {System.out.println("错误");return new ResponseEntity<>("出错了", NOT_EXTENDED);}@ExceptionHandler(value = Exception.class)@ResponseBodypublic String jsonHandler(HttpServletRequest request, Exception e) throws Exception {log(e, request);StringWriter sw = new StringWriter();PrintWriter pw = new PrintWriter(sw);e.printStackTrace(pw);//发送邮件mailService.sendSimpleMail("wuweifeng@XXXX.com", "异常", sw.toString());return "发生异常";}private void log(Exception ex, HttpServletRequest request) {logger.error("************************异常开始*******************************");logger.error("请求地址:" + request.getRequestURL());Enumeration enumeration = request.getParameterNames();logger.error("请求参数");while (enumeration.hasMoreElements()) {String name = enumeration.nextElement().toString();logger.error(name + "---" + request.getParameter(name));}StackTraceElement[] error = ex.getStackTrace();for (StackTraceElement stackTraceElement : error) {logger.error(stackTraceElement.toString());}logger.error("************************异常结束*******************************");}
}

当有异常时会进入被@ExceptionHandler标注的方法中,在该方法里做异常日志的记录和发邮件的逻辑。

手动触发个异常,看看结果

可以看到已经收到邮件了。

SpringBoot拦截全局异常并发送邮件给指定邮箱相关推荐

  1. SpringBoot 自定义全局异常处理器

    SpringBoot自定义全局异常处理器 一.maven依赖 二.GlobalExceptionHandler.java 三.ResponseStandard.java 四.logback.xml 五 ...

  2. SpringBoot(6) SpringBoot配置全局异常

    SpringBoot(6) SpringBoot配置全局异常 参考文章: (1)SpringBoot(6) SpringBoot配置全局异常 (2)https://www.cnblogs.com/pl ...

  3. Springboot捕获全局异常:MethodArgumentNotValidException

    Springboot捕获全局异常:MethodArgumentNotValidException 控制器 方法上添加@Valid注解 @PostMapping("/update") ...

  4. 静态html使用js发送邮件,html实现邮箱发送邮件_js发送邮件至指定邮箱功能

    在前端开发中,JavaScript并没有提供直接操作Email邮箱的功能方法,但是遇到这样的需求,我们应该如何实现js发送邮件至指定邮箱功能呢?下面列举能够在通过前端实现邮件发送的几种方式: 方式一: ...

  5. 定时运行python脚本并发送邮件_python实现定时发送邮件到指定邮箱

    本文实例为大家分享了python实现定时发送邮件到指定邮箱的具体代码,供大家参考,具体内容如下 整个链路:传感器采集端采集数据,边缘端上传数据库,从数据库拿到数据. 产品端有个自动出报告的需求,并且希 ...

  6. 静态html使用js发送邮件,科技常识:html实现邮箱发送邮件_js发送邮件至指定邮箱功能...

    今天小编跟大家讲解下有关html实现邮箱发送邮件_js发送邮件至指定邮箱功能 ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了有关html实现邮箱发送邮件_js发送邮件至指定邮箱功能 的相关资料 ...

  7. 一种获取公网ip地址并发送邮件至指定邮箱的实现方法

    背景   在之前一篇文章中介绍了利用路由器的端口映射功能实现内网穿透的方法.   ubuntu SSH内网穿透 + Vscode远程访问   在实际的使用过程中,发现这一实现途径存在一些不足之处,即当 ...

  8. CentOS 7实现SHEEL脚本监控磁盘空间达到指定阈值时发送邮件至指定邮箱

    实现需求:CentOS 7实现SHEEL脚本监控磁盘空间达到指定阈值时发送邮件至指定邮箱 操作环境:VWware下的CentOS 7.9 一.安装配置mailx CentOS 7自带mailx软件包, ...

  9. CentOS7下mysql定时备份并发送邮件到指定邮箱脚本

    CentOS7下mysql定时备份并发送邮件到指定邮箱脚本 网上有对应的教程,但是使用的mutt发送的邮件. 我从昨晚九点开始搞,搞到凌晨三点都没弄好,早上又搞了一早上也没弄好.因为网上的教程太老,或 ...

  10. h5邮件的邮箱 支持_html实现邮箱发送邮件_js发送邮件至指定邮箱功能

    在前端开发中,JavaScript并没有提供直接操作Email邮箱的功能方法,但是遇到这样的需求,我们应该如何实现js发送邮件至指定邮箱功能呢?下面列举能够在通过前端实现邮件发送的几种方式: 方式一: ...

最新文章

  1. python爬虫教程书-Python 爬虫:把廖雪峰教程转换成 PDF 电子书
  2. dataframe的multiIndex在次级index上做筛选
  3. ios c语言头文件,iOS开发 -- C语言基础12(预处理指令)
  4. c语言编写程序计算行列式值,新手作品:行列式计算C语言版
  5. 蓝桥杯 2017 国赛B组C/C++【对局匹配】
  6. poj 1426 BFS
  7. exchange无法收发邮件_SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送
  8. [工具] PicGo + smms 构建图床
  9. 系统学习NLP(二十六)--NBSVM
  10. html游戏导出存档,switch怎么导出存档-switch导出存档教程
  11. 用Java开发数独游戏,源程序与源代码全部开放
  12. 基于微信小程序的鲜花销售系统毕业设计源码
  13. latex补集怎么打
  14. RFSoC应用笔记 - RF数据转换器 -09- RFSoC关键配置之RF-DAC内部解析(三)
  15. cache和register的区别
  16. 第七章——数据挖掘(2)
  17. 2/3/4/5G频段 带宽介绍
  18. IdentityServer4实战详解
  19. 场内指数基金(ETF)有哪些(附完整名单)
  20. Linux 编程之进程篇:调度、优先级、亲和性和资源限制

热门文章

  1. linux查看网卡物理编号_Linux下查看网卡信息
  2. Roboware (ROS IDE)字体设置
  3. Docker Desktop 安装使用教程
  4. 顺序表的十个基本操作(全)
  5. base64的原理及优缺点
  6. 一图掌握ICT项目管理流程图【实例】
  7. 前端实现在线预览word(docx),pdf,excel类型的文件
  8. 修改棋牌服务器,关于棋牌服务器的一些程序搭建和数据应用步骤
  9. win10千万不要重置_小白不要再用“一键重装系统”了,后果很严重!
  10. 免费45天WPS稻壳会员领取