导读

  最近手头上要负责整个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";
}
}

SpringBoot 整合邮件oh-my-email 实现发送邮件功能的更多相关文章

  1. Springboot】Springboot整合邮件服务(HTML/附件/模板-QQ、网易)

    介绍 邮件服务是常用的服务之一,作用很多,对外可以给用户发送活动.营销广告等:对内可以发送系统监控报告与告警. 本文将介绍Springboot如何整合邮件服务,并给出不同邮件服务商的整合配置. 如图所 ...

  2. springboot整合邮件

    一.邮件相关知识补充 SMTP(Simple Mail Transfer Protocol) 即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式.SMTP协议属 ...

  3. springboot系列九,springboot整合邮件服务、整合定时任务调度

    一.整合邮件服务 如果要进行邮件的整合处理,那么你一定需要有一个邮件服务器,实际上 java 本身提供有一套 JavaMail 组件以实现邮件服务器的搭建,但是这个搭建的服务器意义不大,因为你现在搭建 ...

  4. SpringBoot整合Redis使用Restful风格实现CRUD功能

    前言 本篇文章主要介绍的是SpringBoot整合Redis,使用Restful风格实现的CRUD功能. Redis 介绍 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-valu ...

  5. SpringBoot整合邮件发送

    本节介绍SpringBoot项目如何快速配置和发送邮件,包括简单的邮件配置.发送简单邮件.发送HTML邮件.发送携带附件的邮件等. 示例源码在:https://github.com/laolunsi/ ...

  6. springboot整合邮件发送(163邮箱发送为例)

    先登录163邮箱获取授权  勾选后安装提示会叫你设置授权密码之类的:记住授权的密码 1.引入maven依赖 <dependency> <groupId>org.springfr ...

  7. springboot整合项目-商城个人头像上传功能

    上传头像的功能 持久层 1.sql语句的规划 avatar varchar(50) str - 字节流 将对象文件保存在操作系统上,然后在把这个文件的路径个记录下来,保存在avatar中,因为相比于字 ...

  8. SpringBoot系列九:SpringBoot服务整合(整合邮件服务、定时调度、Actuator监控)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 服务整合 2.背景 在进行项目开发的时候经常会遇见以下的几个问题:需要进行邮件发送.定时的任务调 ...

  9. SpringBoot整合Swagger和Actuator

    前言 本篇文章主要介绍的是SpringBoot整合Swagger(API文档生成框架)和SpringBoot整合Actuator(项目监控)使用教程. SpringBoot整合Swagger 说明:如 ...

随机推荐

  1. Luogu P3200 [HNOI2009]有趣的数列

    题意 给定 \(n\),求有多少个长度为 \(2n\) 的排列 \(p\) 满足 对于 \(1\leq i\leq n\),\(p_{2i-1}<p_{2i}\). \(p_1<p_3&l ...

  2. python数据类型之tuple(元组)

    tuple元组 关注公众号"轻松学编程"了解更多. 1.概述 本质上是一种有序的集合,和列表非常的相似,列表使用[]表示,元组使用**()**表示. 特点:一旦初始化,就不能发生改 ...

  3. 计算机二级考试:Java

    目录 第 1 章 Java 语言概论 第 2 章 基本数据类型 2.1 概述 2.1.1 标识符 2.1.2 关键字 2.1.3 常量 2.2 基本数据类型 第 3 章 运算符和表达式 3.2 算术运 ...

  4. 电脑查看当前自己的wifi密码

    菜单+R 输入control  点击确认.

  5. Thinkphp3.2 cms之分类管理

    四.分类管理 <?php namespace Admin\Controller; use Think\Controller; class CateController extends Contr ...

  6. 关于layui图片/文件上传

    一:常规使用   普通文件上传 (传入服务器一张图片) 1.前台代码: <!DOCTYPE html><html><head> <meta charset=& ...

  7. ubuntu下创建http服务器

    使用ubuntu搭建一个简单的http服务器安装apache21.sudo apt-get update2.sudo apt-get install apache2 安装成功后,再/etc/apach ...

  8. fashion数据集训练

    下载数据集 fashion数据集总共有7万张28*28像素点的灰度图片和标签,涵盖十个分类:T恤.裤子.套头衫.连衣裙.外套.凉鞋.衬衫.运动鞋.包.靴子. 其中6万张用于训练,1万张用于测试. im ...

  9. GDB的原理

    gdb调试不管是本地调试还是远程调试,都是基于ptrace系统调用来实现. ptrace系统调用提供了一种方法,让父进程可以观察和控制其它进程的执行,检查和改变其核心映像及寄存器.主要用来实现断点调试 ...

  10. 【java从入门到精通】day-07-逻辑运算符-位运算符-条件运算符-扩展赋值运算符

    逻辑与(&&).或(||).非(!) 示例: package operator;​public class Demo05 {    public static void main(St ...