导读

  最近手头上要负责整个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. symfony3.4 配置高效的邮箱swiftmailer插件

    网站经常需要邮件发送,symfony里面swiftmailerBundle是一个非常并且稳定的发送邮件的第三方插件. 我们来看一下symfony里面的邮件怎么配置. 第一步我们先下载bundle: c ...

  2. Java学习的第十八天

    1abstract 综合实例 2.不知道为什么综合实例中的Scanner报错 3.明天解决问题并学习第六章初步知识

  3. k8s中pod的yaml文件全面解读

    apiVersion: v1 #必选,版本号,例如v1,版本号必须可以用 kubectl api-versions 查询到 . kind: Pod #必选,Pod metadata: #必选,元数据 ...

  4. [Luogu P3119] [USACO15JAN]草鉴定Grass Cownoisseur (缩点+图上DP)

    题面 传送门:https://www.luogu.org/problemnew/show/P3119 Solution 这题显然要先把缩点做了. 然后我们就可以考虑如何处理走反向边的问题. 像我这样的 ...

  5. sync_with_stdio(false)的副作用

    sync_with_stdio()的一个特性 水一篇随笔 其实对于用快读的大佬来说没什么用,但还是提一下 ios::sync_with_stdio(false)用处是"关闭同步", ...

  6. 【SpringBoot】10.SpringBoot文件上传

    SpringBoot整合Thymeleaf 1.创建Thymeleaf的入门项目 maven构建简单项目 修改pom文件添加thymeleaf的坐标 <!-- thymeleaf的坐标 --&g ...

  7. 用npm安装插件时报错: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents)

    在做前端项目的时候执行命令: npm install --save-dev file-loader@1.1.6 --registry=https://registry.npm.taobao.org 出 ...

  8. tp3.2自动验证

    <?php namespace Home\Model; use Think\Model; class UserModel extends Model{ protected $patchValid ...

  9. css布局中的BFC

    1.BFC的区域会与float的元素区域重叠 2.计算BFC的高度时,浮动子元素也参与计算 3.BFC就是页面上的一个隔离的独立容器,容器里面的子元素是不会影响到外面的元素 4.BFC意为" ...

  10. Python爬取B站耗子尾汁、不讲武德出处的视频弹幕

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 前言 耗子喂汁是什么意思什么梗呢?可能很多人不知道,这个梗是出自马保国,经常上网的人可能听说过这个 ...