SpringBoot 整合邮件oh-my-email 实现发送邮件功能

导读

  最近手头上要负责整个Message Gateway服务的搭建,涉及到:微信推送(点我直达)、短信、邮件等等,到github上发现有个微型的开源邮件框架,整理下来,以备项目中使用到,到时候应该会使用MQ(RocketMQ 点我直达),异步的方式实现,先写一个简单demo。

github官网地址

点我直达

添加依赖

        <dependency>
            <groupId>io.github.biezhi</groupId>
            <artifactId>oh-my-email</artifactId>
            <version>0.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.mitchellbosecke</groupId>
            <artifactId>pebble</artifactId>
            <version>2.2.0</version>
        </dependency>

控制层代码

package com.ybchen.springbootohmyemail.controller;

import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import io.github.biezhi.ome.OhMyEmail;
import io.github.biezhi.ome.SendMailException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static io.github.biezhi.ome.OhMyEmail.SMTP_QQ;

/**
 * @ClassName:EmailController
 * @Description:邮件控制层
 * @Author:chenyb
 * @Date:2020/11/26 11:43 上午
 * @Versiion:1.0
 */
@RestController
public class EmailController {
    // 该邮箱修改为你需要测试的邮箱地址
    private static final String TO_EMAIL = "xxxx@isoftstone.com";

    @PostConstruct
    public void init() {
        // 配置,一次即可
        OhMyEmail.config(SMTP_QQ(false), "543210188@qq.com", "qq邮箱smtp密码");
    }

    @GetMapping("testSendText")
    public String testSendText() throws SendMailException {
        OhMyEmail.subject("这是一封测试TEXT邮件")
                .from("小姐姐的邮箱")
                .to(TO_EMAIL)
                .text("信件内容")
                .send();
        return "发送成功";
    }

    @GetMapping("testSendHtml")
    public String testSendHtml() throws SendMailException {
        OhMyEmail.subject("这是一封测试HTML邮件")
                .from("小姐姐的邮箱")
                .to(TO_EMAIL)
                .html("<h1 font=red>信件内容</h1>")
                .send();
        return "发送成功";
    }

    @GetMapping("testSendAttach")
    public String testSendAttach() throws SendMailException {
        OhMyEmail.subject("这是一封测试附件邮件")
                .from("小姐姐的邮箱")
                .to(TO_EMAIL)
                .html("<h1 font=red>信件内容</h1>")
                .attach(new File("/Users/biezhi/Downloads/hello.jpeg"), "测试图片.jpeg")
                .send();
        return "发送成功";
    }

    @GetMapping("testSendAttachURL")
    public String testSendAttachURL() throws SendMailException {
        try {
            OhMyEmail.subject("这是一封测试网络资源作为附件的邮件")
                    .from("小姐姐的邮箱")
                    .to(TO_EMAIL)
                    .html("<h1 font=red>信件内容</h1>")
                    .attachURL(new URL("https://avatars1.githubusercontent.com/u/2784452?s=40&v=4"), "测试图片.jpeg")
                    .send();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return "发送成功";
    }

    @GetMapping("testPebble")
    public String testPebble() throws IOException, PebbleException, SendMailException {
        PebbleEngine engine = new PebbleEngine.Builder().build();
        PebbleTemplate compiledTemplate = engine.getTemplate("register.html");

        Map<String, Object> context = new HashMap<String, Object>();
        context.put("username", "biezhi");
        context.put("email", "admin@biezhi.me");

        Writer writer = new StringWriter();
        compiledTemplate.evaluate(writer, context);

        String output = writer.toString();
        System.out.println(output);

        OhMyEmail.subject("这是一封测试Pebble模板邮件")
                .from("小姐姐的邮箱")
                .to(TO_EMAIL)
                .html(output)
                .send();
        return "发送成功";
    }
}

测试

多线程并发发送邮件

    @GetMapping("testFile")
    public String testFile(@RequestParam("file") MultipartFile[] files) throws Exception {
        try {
            List<String> listPath = new ArrayList<String>(files.length);
            CountDownLatch countDownLatch=new CountDownLatch(1);
            OhMyEmail ohMyEmail = OhMyEmail.subject("这是一封测试附件的邮件")
                    .from("邮件服务管理员")
                    .to(TO_EMAIL)
                    .html("<h1 font=red>信件内容</h1><br/>邮件测试内容")
                    .attachURL(new URL("https://avatars1.githubusercontent.com/u/2784452?s=40&v=4"), "测试图片.jpeg")
                    .attachURL(new URL("https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg"), "测试图片.jpeg");
            if (files.length>10){
                return "文件个数超过10个";
            }
            if (files.length > 0) {
                File currentFile = new File("");
                String currentFilePath = currentFile.getCanonicalPath() + File.separator + "sendFile" + File.separator;
                for (int i = 0; i < files.length; i++) {
                    MultipartFile multipartFile = files[i];
                    String fullPath = currentFilePath + multipartFile.getOriginalFilename();
                    File destFile = new File(fullPath);
                    destFile.getParentFile().mkdirs();
                    multipartFile.transferTo(destFile);
                    listPath.add(fullPath);
                    System.out.println(fullPath);
                    ohMyEmail.attach(new File(fullPath));
                }
            }
            new Thread(()->{
                try {
                    ohMyEmail.send();
                } catch (SendMailException e) {
                    e.printStackTrace();
                }finally {
                    countDownLatch.countDown();
                    System.out.println("线程减一");
                }
            }).start();
            new Thread(()->{
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < listPath.size(); i++) {
                    File delFile=new File(listPath.get(i));
                    delFile.delete();
                    System.out.println("删除一条");
                }
            }).start();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return "发送成功";
    }

设置上传文件大小

  在application.properties中添加如下

spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB

全局异常拦截超过文件大小

package com.ybchen.springbootohmyemail.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.multipart.MaxUploadSizeExceededException;

/**
 * 异常处理类
 */
@ControllerAdvice
public class CustomExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(CustomExceptionHandle.class);

    //监听这个异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object handle(Exception ex) {
        logger.error("[ 系统异常 ] ===============》 {}", ex);
        return "系统内部错误";
    }
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    @ResponseBody
    public Object handleMaxUploadSizeExceededException(Exception ex) {
        logger.error("[ 系统异常 ] ===============》 {}", ex);
        System.out.println("文件大小超过50MB");
        return "文件大小超过50MB";
    }
}

Java模板引擎替换内容

点我直达

反射获取实体类中的值

点我直达

原文地址:https://www.cnblogs.com/chenyanbin/p/14042642.html