-- 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. vue导航栏制作

    1,在components新建commnn目录,然后再新建nav目录,在此目录下新建nav-bottom.vue文件和nav-item.vue文件 2,nav-bottom.vue中的内容: < ...

  2. 移动端tab切换时下划线的滑动效果

    1.当前 tab 出现下划线的同时,前一个下划线同时消失(出现方向与消失方向保持一致),伴随过渡效果. <!DOCTYPE html><html lang="en" ...

  3. init是一个自定义方法名

    init是一个自定义方法名,用于初始化页面变量.上面的代码表示初始化方法是在当前网页加载后执行的(当浏览器打开网页时,触发窗口对象的onload方法,用上面的代码执行名为init的初始化方法).事实上 ...

  4. Oracle层次查询start with connect by

    博客参考:https://www.cnblogs.com/jerryxing/articles/2339352.html start with connect by 层次查询(Hierarchical ...

  5. 性能测试分析工具nmon文件分析时报错解决办法

    1.使用nmon analyzer V334.xml分析数据时,如果文件过大,可以修改Analyser页签中的INTERVALS的最大值: 2.查找生成的nmon文件中包含的nan,删掉这些数据(需要 ...

  6. deep_learning_neural network梯度下降

    神经网络优化算法:梯度下降法.Momentum.RMSprop和Adam 最近回顾神经网络的知识,简单做一些整理,归档一下神经网络优化算法的知识.关于神经网络的优化,吴恩达的深度学习课程讲解得非常通俗 ...

  7. solr7中文分词包

    刚刚将solr4升级到了solr7.7,发现之前用的mmseg4j中文分词包用的时候会报错,插入新数据是创建索引会有异常 possible analysis error: startOffset mu ...

  8. Linux下计划任务:crontab 命令的权限说明

    Linux下的计划任务: 使用crontab命令来执行调度,在 Linux 下可以通过创建文件 /etc/cron.allow 或者 /etc/cron.deny 来控制权限,如果 /etc/cron ...

  9. 《编译原理》LR 分析法与构造 LR(1) 分析表的步骤 - 例题解析

    <编译原理>LR 分析法与构造 LR(1) 分析表的步骤 - 例题解析 笔记 直接做题是有一些特定步骤,有技巧.但也必须先了解一些基本概念,本篇会通过例题形式解释概念,会容易理解和记忆,以 ...

  10. maven-war-plugin

    Name Type Since Description 默认值 cacheFile File 2.1-alpha-1 包含webapp结构的文件缓存 ${project.build.directory ...