springboot拦截异常信息发送邮件提醒
-- private JavaMailSender sender; 可能会出现注入错误,请注意yam配置文件中格式是否一致;否则会找不到注入的bean
一 发送邮件
在Springboot中发送邮件非常简单。
pom.xml引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
在application.yml里设置发信人的账号、密码
spring:
mail:
host: smtp.qq.com
username: 27255XXXX@qq.com
password: njcvcbdkrofgbhie
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
这个username就是未来发信时的邮箱地址,password是授权码。
这里以普通qq邮箱为例,注意password不是qq密码,而是授权码。

在qq邮箱-设置-账户,找到图片中的地方,开启IMAP/SMTP服务,开启后才能在别的客户端使用该qq邮箱发邮件,然后生成授权码,填写到application.yml的password位置。
然后就可以使用该邮箱作为发件人了。
看一下发邮件的具体代码,参考http://blog.csdn.net/clementad/article/details/51833416
package com.zhx.commonservice.common.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; /**
* @Author: SimonHu
* @Date: 2019/5/23 9:04
* @Description:
*/
@Service
public class MailService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private 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();
String[] toRecive = to.split(",");
message.setFrom(from);
message.setTo(toRecive);
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 {
String[] toRecive = to.split(",");
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toRecive);
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 {
String[] toRecive = to.split(",");
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toRecive);
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 {
String[] toRecive = to.split(",");
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(toRecive);
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());
@Autowired
private MailService mailService; /**
* 在controller里面内容执行之前,校验一些参数不匹配啊,Get post方法不对啊之类的
*/
@Override
protected 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)
@ResponseBody
public 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("************************异常结束*******************************");
}
}
springboot拦截异常信息发送邮件提醒的更多相关文章
- 第三节:使用Log4net和过滤器记录异常信息,返回异常给前端
上次面试,遇到,在项目中如何处理业务异常和代码异常,使用txt记录异常信息后,如何直接区分出异常的类型,异常怎么分类处理,希望大家能帮我提出宝贵的意见,完善处理异常, 统一返回参数 public cl ...
- 基于springboot实现http响应异常信息国际化
背景 国际化是指在设计软件,将软件与特定语言及地区脱钩的过程.当软件被移植到不同的语言及地区时,软件本身不用做内部工程上的改变或修正. 本文提到的异常响应信息国际化是指:前端向后台发起请求,后台在处理 ...
- springboot 1.3.5升级1.5.9后 默认使用tomcat 8.5版本 get请求报400 异常信息为 The valid characters are defined in RFC 7230 and RFC 3986
1.springboot 1.3.5升级1.5.9后 默认使用tomcat 8.5版本而之前用的是tomcat7 get请求报400 异常信息为 The valid characters are ...
- Android 后台发送邮件 (收集应用异常信息+Demo代码)
上一次说了如何收集我们已经发布的应用程序的错误信息,方便我们调试完善程序.上次说的收集方法主要是把收集的信息通过Http的post请求把相关的异常信息变成请求参数发送到服务器.这个对做过web开发的人 ...
- springboot 统一管理异常信息
新建ResponseEntityExceptionHandler的继承类:(依然,需要入口类扫描) /** * @author sky * @version 1.0 */ @ControllerAdv ...
- springboot全局异常拦截源码解读
在springboot中我们可以通过注解@ControllerAdvice来声明一个异常拦截类,通过@ExceptionHandler获取拦截类抛出来的具体异常类,我们可以通过阅读源码并debug去解 ...
- SpringBoot全局异常拦截
SpringBoot全局异常捕获 使用到的技能 @RestControllerAdvice或(@ControllerAdvice+@ResponseBody) @ExceptionHandler 代码 ...
- springboot + 拦截器 + 注解 实现自定义权限验证
springboot + 拦截器 + 注解 实现自定义权限验证最近用到一种前端模板技术:jtwig,在权限控制上没有用springSecurity.因此用拦截器和注解结合实现了权限控制. 1.1 定义 ...
- springboot 全局异常捕获,异常流处理业务逻辑
前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...
随机推荐
- sass之mixin的全局引入(vue3.0)
sass之mixin的全局引入(vue3.0) 1.scss文件(mixin.scss) /* 渐变 */ @mixin gradual($color, $color1){ background: $ ...
- js之语句(表达式语句,复合语句,声明语句)
语句就是JavaScript整句或命令,以分号结束,用来执行以使某件事发生.下面将介绍三种语句:表达式语句,复合语句,声明语句. 一.表达式语句 表达式语句是javascript中最简单的语句 < ...
- Django基础第一篇
目录 1.Django MTV框架简介 2.基础命令创建项目的配置说明 3.前后端交互案例 4.基于数据库实现数据交互增删改查 Django简介 Django框架的设计模式借鉴了MVC的思想,和MVC ...
- vue中的常用三元
点击事件的三元 <el-button type="primary" @click="edit == 'mod' ? sureModify() : submit()& ...
- bisect:维护一个有序的列表
介绍 bisect模块实现了一个算法来向列表中插入元素,同时仍然保证列表有序 有序插入 import bisect ''' 可以使用bisect.insort向一个列表中插入元素 ''' values ...
- SQL语句复习【专题七】
SQL语句复习[专题七] 完整性约束分类1)域完整性约束(非空not null,检查check)2)实体完整性约束(唯一unique,主键primary key)3)参照完整性约束(外键foreign ...
- GMT、UTC、UNIX时间戳、时区
GMT.UTC.CTS: UTC时间:世界协调时间(UTC)是世界上不同国家用来调节时钟和时间的主要时间标准,也就是零时区的时间.UTC是以原子时秒长为基础,在时刻上尽量接近于GMT的一种时间计量系统 ...
- except用法
#!/usr/bin/expect set timeout 20 spawn ssh -l root 172.25.254.102 expect "(yes/no)?" send ...
- da面板修改SSH端口号
进入da面板,找到管理工具菜单下的文件编辑器,点击进入,选择所要编辑的文件/etc/ssh/sshd_config 点击右侧的显示文件,即可打开该文件进行编辑,例如可以将原始端口22修改为 33 #P ...
- View相关面试问题-ListView缓存面试问题讲解
什么是ListView: ListView就是一个能数据集合以动态滚动的方式显示在用户界面上的View. ListView适配器模式: 有了Adapter可以将数据源与view进行分离~ ListVi ...