springboot攔截異常信息發送郵件提醒

-- private JavaMailSender sender; 可能會出現注入錯誤,請注意yam配置文件中格式是否一致;不然會找不到注入的beanhtml

一 發送郵件

在Springboot中發送郵件很是簡單。java

pom.xml引入maven依賴web

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

在application.yml裏設置發信人的帳號、密碼spring

spring:
  mail:
    host: smtp.qq.com
    username: 27255XXXX@qq.com
    password: njcvcbdkrofgbhie
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

這個username就是將來發信時的郵箱地址,password是受權碼。json

這裏以普通qq郵箱爲例,注意password不是qq密碼,而是受權碼。併發

在qq郵箱-設置-帳戶,找到圖片中的地方,開啓IMAP/SMTP服務,開啓後才能在別的客戶端使用該qq郵箱發郵件,而後生成受權碼,填寫到application.yml的password位置。mvc

而後就能夠使用該郵箱做爲發件人了。app

看一下發郵件的具體代碼,參考http://blog.csdn.net/clementad/article/details/51833416maven

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);
        }
    }
}

而後就能夠使用裏面的方法發郵件了。
能夠先寫個簡單的測試類,調用ide

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("************************異常結束*******************************");
    }
}
相關文章
相關標籤/搜索