导读

  最近手头上要负责整个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. modbus协议开关量采集模块

    modbus协议开关量采集模块是指的使用Modbus协议的进行信号的采集与控制的一种设备. Modbus 协议设备都具有唯一的 Modbus 地址,众山 DTU 默认 Modbus 地址为 100,用 ...

  2. python机器学习的开发流程

    标准机器学习的开发编程流程 关注公众号"轻松学编程"了解更多. 一.流程 标准机器学习的开发编程流程: 1.获取数据(爬虫.数据加载.业务部门获取) 2.数据建模(摘选样本数据(特 ...

  3. xshell连接windows10子系统ubuntu

    修改端口 cd /etc/ssh#备份sudo cp sshd_config sshd_config.baksudo vim sshd_config修改sshd_config Port 2233 #修 ...

  4. rclone 云盘同步工具的正确打开方式

    Rclone 是一款的命令行工具,支持在不同对象存储.网盘间同步.上传.下载数据. 官网网址:https://rclone.org/ Github 项目:https://github.com/ncw/ ...

  5. CF777E Hanoi Factory

    DP单调栈优化 看到这道题可以很自然的想到DP 设$dp[i]$表示最后一个$ring$为$i$的最大高度 首先将$b$为第一关键字,$a$为第二关键字,升序排序元素 那么对于$i$来说,它下面的$r ...

  6. Docker - 解决重新进入容器后,环境变量失效的问题

    问题背景 在容器中,在 /etc/profile . /etc/environment 设置了环境变量 退出容器,重新进入容器 刚刚设置的环境变量失效了 解决办法 将环境变量设置在 /root/.ba ...

  7. Python 中 'unicodeescape' codec can't decode bytes in position XXX: trun错误解决方案

    window 读取文件可以用\,但是在字符串中\是被当作转义字符来使用,'C:\Users\FrankYuan\Pictures\Camera Roll\WIN_20161010_08_51_57_P ...

  8. Linux 笔记1

    linux netstat -an | grep 8081 查看端口进程 window netstat -ano|findstr "1433" taskkill -pid ** - ...

  9. docker生产——容器通信

    简介 在接触docker的第一天起,大家应该就知道:docker容器使用沙箱机制,相互之间没有接口,一般情况下内部访问通过IP+端口.本地容器默认分配的IP极易发生变化,所以靠IP+端口访问的方式缺失 ...

  10. 解决SSH显示中文乱码的问题(cent os7)

    用SSH连接服务器显示中文乱码,试过修改SSH端,不成功.这次从服务器端下手 1.先查看服务器现有的字符集 [root@dm01 ~]# locale -a 在结果中找到 如果没有支持的字符集就需要安 ...