-- 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拦截异常信息发送邮件提醒的更多相关文章

  1. 第三节:使用Log4net和过滤器记录异常信息,返回异常给前端

    上次面试,遇到,在项目中如何处理业务异常和代码异常,使用txt记录异常信息后,如何直接区分出异常的类型,异常怎么分类处理,希望大家能帮我提出宝贵的意见,完善处理异常, 统一返回参数 public cl ...

  2. 基于springboot实现http响应异常信息国际化

    背景 国际化是指在设计软件,将软件与特定语言及地区脱钩的过程.当软件被移植到不同的语言及地区时,软件本身不用做内部工程上的改变或修正. 本文提到的异常响应信息国际化是指:前端向后台发起请求,后台在处理 ...

  3. 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 ...

  4. Android 后台发送邮件 (收集应用异常信息+Demo代码)

    上一次说了如何收集我们已经发布的应用程序的错误信息,方便我们调试完善程序.上次说的收集方法主要是把收集的信息通过Http的post请求把相关的异常信息变成请求参数发送到服务器.这个对做过web开发的人 ...

  5. springboot 统一管理异常信息

    新建ResponseEntityExceptionHandler的继承类:(依然,需要入口类扫描) /** * @author sky * @version 1.0 */ @ControllerAdv ...

  6. springboot全局异常拦截源码解读

    在springboot中我们可以通过注解@ControllerAdvice来声明一个异常拦截类,通过@ExceptionHandler获取拦截类抛出来的具体异常类,我们可以通过阅读源码并debug去解 ...

  7. SpringBoot全局异常拦截

    SpringBoot全局异常捕获 使用到的技能 @RestControllerAdvice或(@ControllerAdvice+@ResponseBody) @ExceptionHandler 代码 ...

  8. springboot + 拦截器 + 注解 实现自定义权限验证

    springboot + 拦截器 + 注解 实现自定义权限验证最近用到一种前端模板技术:jtwig,在权限控制上没有用springSecurity.因此用拦截器和注解结合实现了权限控制. 1.1 定义 ...

  9. springboot 全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

随机推荐

  1. JavaScript中with不推荐使用,为什么总是出现在面试题中?

    with的基本使用 尴尬的with关键字 一.with的基本使用 with是用来扩展语句作用域的,什么意思呢?先来看看语法和示例: 语法: with(expression){ statement } ...

  2. Ajax与JSON,XML,PHP

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. 分布式缓存Redis+Memcached经典面试题和答案

    Redis相比memcached有哪些优势? (1) memcached所有的值均是简单的字符串,redis作为其替代者,支持更为丰富的数据类型 (2) redis的速度比memcached快很多 ( ...

  4. MySQL踩坑及MySQL解压版安装

    MySQL默认当前时间: MySQL5.5版本以下是不支持:datetime default now() 的,只能写成 timestamp default now() ; 而MySQL5.6以上是支持 ...

  5. ubuntu install opencv

    1. install the newest opencv version pip install opencv-python

  6. 网络初级篇之STP(BPDU详解与STP故障恢复)

    一.BPDU包含的参数 通过STP的原理,我们学习了红色部分的字段(根桥ID.根路径开销.桥ID.端口ID).现在讲解一下黄色部分的字段(类型.计时器.老化时间.访问时间) 1.(BPDU Type) ...

  7. socket 测试工具java

    SocketTest.jar http://sockettest.sourceforge.net/

  8. winform Combox绑定数据时不触发SelectIndexChanged事件

    做了一个仓库选择的联动,选了仓库选其下的货区,选了货区选其下的货架分区.每个combox初始化.绑定数据是都会触发SelectIndexChanged事件,相当头疼. 后来无意中在网上看到了一种方法— ...

  9. Tampermonkey油猴脚本管理插件-最强浏览器插件的安装使用全攻略

      对于接触过谷歌浏览器插件的“玩家”们来说,应该没有人没听说过Tampermonkey用户脚本管理器,也就是中文所说的“油猴”这个chrome插件了. 油猴号称全商店最强的浏览器插件绝非浪得虚名,一 ...

  10. u-boot下的DM驱动模型 阶梯状 (转)

    U-boot 下DM驱动模型的相关笔记要注意的关键两点: DM驱动模型的一般流程bind->ofdata_to_platdata(可选)->probe    启动,bind操作时单独完成的 ...