玩转 SpringBoot 2 之发送邮件篇
前言
通过本文你将了解到SpringBoot 2 中发送邮件使用教程,具体详细内容如下:
- 发送普通的邮件
- 发送html格式邮件
- 发送html 中带图片的邮件
- 发送带附件的邮件
阅读前需要你必须了解如何搭建 SpringBoot 项目,
简单介绍
Spring 提供了JavaMailSender 接口帮我们来实现邮件的发送。在SpringBoot 更是提供了邮件的发送的 starter 依赖来简化邮件发送代码的开发 。
实战操作演示
邮件功能开发前准备
第一步:先引入mail 的 starter依赖在pom.xm中,具体代码如下:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
第二步:添加的配置信息 我们这里是通过yml 方式进行配置
spring:mail:host: smtp.126.comusername: 邮箱用户名password: 邮箱密码properties:mail:smtp:auth: true # 需要验证登录名和密码starttls:enable: true # 需要TLS认证 保证发送邮件安全验证required: true
发送普通的邮件
开发步骤:
第一步:通过 SimpleMailMessage 设置发送邮件信息,具体信息如下:
- 发送人(From)
- 被发送人(To)
- 主题(Subject)
- 内容(Text)
第二步:通过JavaMailSender send(SimpleMailMessage simpleMailMessage)
方法发送邮件。
具体代码如下:
package cn.lijunkui.mail;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.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;@Service
public class MailService {private final Logger logger = LoggerFactory.getLogger(this.getClass());@Autowiredprivate JavaMailSender sender;@Value("${spring.mail.username}")private String formMail;public void sendSimpleMail(String toMail,String subject,String content) {SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setFrom(formMail);simpleMailMessage.setTo(toMail);simpleMailMessage.setSubject(subject);simpleMailMessage.setText(content);try {sender.send(simpleMailMessage);logger.info("发送给"+toMail+"简单邮件已经发送。 subject:"+subject);}catch (Exception e){logger.info("发送给"+toMail+"send mail error subject:"+subject);e.printStackTrace();}}
}
发送 html 格式邮件
开发步骤:
第一步:通过JavaMailSender 的 createMimeMessage() 创建 MimeMessage
对象实例
第二步:将 MimeMessage 放入到MimeMessageHelper 构造函数中,并通过MimeMessageHelper 设置发送邮件信息。(发送人, 被发送人,主题,内容)
第三步:通过JavaMailSender send(MimeMessage mimeMessage)发送邮件。
具体代码如下:
public void sendHtmlMail(String toMail,String subject,String content) {MimeMessage mimeMessage = sender.createMimeMessage();try {MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);mimeMessageHelper.setTo(toMail);mimeMessageHelper.setFrom(formMail);mimeMessageHelper.setText(content,true);mimeMessageHelper.setSubject(subject);sender.send(mimeMessage);logger.info("发送给"+toMail+"html邮件已经发送。 subject:"+subject);} catch (MessagingException e) {logger.info("发送给"+toMail+"html send mail error subject:"+subject);e.printStackTrace();}}
发送 html 中带图片的邮件
发送 html 中带图片的邮件和发送 html邮件操作基本一致,不同的是需要额外在通过MimeMessageHelper addInline 的方法去设置图片信息。
开发步骤:
- 定义html 嵌入的 image标签中 src 属性 id 例如 <img src=“cid:image1”/>
- 设置MimeMessageHelper通过addInline 将cid 和文件资源进行指定即可
具体代码如下:
package cn.lijunkui.mail;public class InlineResource {private String cid;private String path;public String getCid() {return cid;}public void setCid(String cid) {this.cid = cid;}public String getPath() {return path;}public void setPath(String path) {this.path = path;}public InlineResource(String cid, String path) {super();this.cid = cid;this.path = path;}
}/*** 发送静态资源(一般是图片)的邮件* @param to* @param subject* @param content 邮件内容,需要包括一个静态资源的id,比如:<img src=\"cid:image\" >* @param resourceist 静态资源list*/public void sendInlineResourceMail(String to, String subject, String content,List<InlineResource> resourceist){MimeMessage message = sender.createMimeMessage();try {//true表示需要创建一个multipart messageMimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(formMail);helper.setTo(to);helper.setSubject(subject);helper.setText(content, true);for (InlineResource inlineResource : resourceist) {FileSystemResource res = new FileSystemResource(new File(inlineResource.getPath()));helper.addInline(inlineResource.getCid(),res);}sender.send(message);logger.info("嵌入静态资源的邮件已经发送。");} catch (MessagingException e) {logger.error("发送嵌入静态资源的邮件时发生异常!", e);}}
发送带附件的邮件
发送带附件的邮件和发送html 操作基本一致,通过MimeMessageHelper设置邮件信息的时候,将附件通过FileSystemResource 进行包装,然后再通过 MimeMessageHelper addAttachment 设置到发送邮件信息中即可。
具体代码如下:
public void sendAttachmentsMail(String toMail,String subject,String content,String filePath) {MimeMessage message = sender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(formMail);helper.setTo(toMail);helper.setSubject(subject);helper.setText(content, true);FileSystemResource file = new FileSystemResource(new File(filePath));String fileName = filePath.substring(filePath.lastIndexOf("/"));helper.addAttachment(fileName, file);sender.send(message);logger.info("发送给"+toMail+"带附件的邮件已经发送。");} catch (MessagingException e) {e.printStackTrace();logger.error("发送给"+toMail+"带附件的邮件时发生异常!", e);}}
测试
发送普通的邮件测试
在开发中建议大家将每个编写完的小功能进行测试 养成良好的开发习惯。
测试用例:
package cn.lijunkui.mail;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@SpringBootTest
@RunWith(SpringRunner.class)
public class MailServiceTest {@Autowiredprivate MailService mailService;@Testpublic void sendSimpleMail() {mailService.sendSimpleMail("1165904938@qq.com", "这是一个测试邮件", "这是一个测试邮件");}}
测试结果:
发送 html 格式邮件测试
@Testpublic void snedHtmlMail() {String html= "<!DOCTYPE html>\r\n" + "<html>\r\n" + "<head>\r\n" + "<meta charset=\"UTF-8\">\r\n" + "<title>Insert title here</title>\r\n" + "</head>\r\n" + "<body>\r\n" + " <font color=\"red\">发送html</font>\r\n" + "</body>\r\n" + "</html>";mailService.sendHtmlMail("1165904938@qq.com", "这是一个测试邮件", html);}
发送 html 中带图片的邮件测试
测试用例:
@Testpublic void sendInlineResourceMail() {String html= "<!DOCTYPE html>\r\n" + "<html>\r\n" + "<head>\r\n" + "<meta charset=\"UTF-8\">\r\n" + "<title>Insert title here</title>\r\n" + "</head>\r\n" + "<body>\r\n" + "<img src=\"cid:image1\"/> "+"<img src=\"cid:image2\"/> "+" <font color=\"red\">发送html</font>\r\n" + "</body>\r\n" + "</html>";List<InlineResource> list = new ArrayList<InlineResource>();String path = MailServiceTest.class.getClassLoader().getResource("image.jpg").getPath();InlineResource resource = new InlineResource("image1",path);InlineResource resource2 = new InlineResource("image2",path);list.add(resource2);list.add(resource);mailService.sendInlineResourceMail("1165904938@qq.com", "这是一个测试邮件", html,list);}
测试结果:
发送带附件的邮件测试
测试用例:
@Testpublic void sendAttachmentsMail() {String html= "<!DOCTYPE html>\r\n" + "<html>\r\n" + "<head>\r\n" + "<meta charset=\"UTF-8\">\r\n" + "<title>Insert title here</title>\r\n" + "</head>\r\n" + "<body>\r\n" + " <font color=\"red\">发送html</font>\r\n" + "</body>\r\n" + "</html>";String path = MailServiceTest.class.getClassLoader().getResource("image.jpg").getPath();mailService.sendAttachmentsMail("1165904938@qq.com", "这是一个测试邮件", html, path);}
测试结果:
小结
发送普通邮件通过 SimpleMailMessage 封装发送邮件的消息,发送 html 格式和附件邮件通过MimeMessageHelper 封装发送邮件的消息,最后通过 JavaMailSender 的send方法进行发送即可。如果你还没有操作过,还等什么赶紧操作一遍吧。
代码示例
我本地环境如下:
- SpringBoot Version: 2.1.0.RELEASE
- Apache Maven Version: 3.6.0
- Java Version: 1.8.0_144
- IDEA:Spring Tools Suite (STS)
整合过程如出现问题可以在我的GitHub 仓库 springbootexamples 中模块名为 spring-boot-2.x_mail 项目中进行对比查看
GitHub:https://github.com/zhuoqianmingyue/springbootexamples
参考文献
https://docs.spring.io/spring/docs/5.0.10.RELEASE/spring-framework-reference/integration.html#mail
玩转 SpringBoot 2 之发送邮件篇相关推荐
- 玩转 SpringBoot 2 快速整合 | RESTful Api 篇
概述 RESTful 是一种架构风格,任何符合 RESTful 风格的架构,我们都可以称之为 RESTful 架构.我们常说的 RESTful Api 是符合 RESTful 原则和约束的 HTTP ...
- 玩转springboot:默认静态资源和自定义静态资源实战
点个赞,看一看,好习惯!本文 GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了3个月总结的一线大厂Java面试总结,本人已拿腾 ...
- 玩转 SpringBoot 2 之整合 JWT 下篇
前言 在<玩转 SpringBoot 2 之整合 JWT 上篇> 中介绍了关于 JWT 相关概念和JWT 基本使用的操作方式.本文为 SpringBoot 整合 JWT 的下篇,通过解决 ...
- SpringBoot运维实用篇
SpringBoot2零基础到项目实战-基础篇 SpringBoot运维实用篇 从此刻开始,咱们就要进入到实用篇的学习了.实用篇是在基础篇的根基之上,补全SpringBoot的知识图谱.比如在基础篇中 ...
- onresize事件会被多次触发_玩转SpringBoot之通过事件机制参与SpringBoot应用的启动过程...
生命周期和事件监听 一个应用的启动过程和关闭过程是归属到"生命周期"这个概念的范畴. 典型的设计是在启动和关闭过程中会触发一系列的"事件",我们只要监听这些事件 ...
- @retention注解作用_分分钟带你玩转SpringBoot自定义注解
在工作中,我们有时候需要将一些公共的功能封装,比如操作日志的存储,防重复提交等等.这些功能有些接口会用到,为了便于其他接口和方法的使用,做成自定义注解,侵入性更低一点.别人用的话直接注解就好.下面就来 ...
- SpringBoot (一) :入门篇
SpringBoot (一) :入门篇 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使 ...
- 玩转 SpringBoot 2 之整合 JWT 上篇
前言 该文主要带你了解什么是 JWT,以及JWT 定义和先关概念的介绍,并通过简单Demo 带你了解如何使用 SpringBoot 2 整合 JWT. 介绍前在这里我们来探讨一下如何学习一门新的技术, ...
- ASP.NET中常用功能代码总结(1)——发送邮件篇
ASP.NET中常用功能代码总结(1)--发送邮件篇<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office: ...
最新文章
- Sketchup插件Vray户外场景设计渲染教程 Vray Next For Sketchup Exterior
- Java泛型进阶 - 如何取出泛型类型参数
- DFS、栈、双向队列:CF264A- Escape from Stones
- python爬虫的硬件配置_python爬虫之redis环境简单部署
- java icmp_java – 为什么没有ICMP指令?
- jsp标签 判断 余数_程序员的数学基础课(三)余数与迭代法
- LinkedList 方法知识点
- python打包exe黑框一闪而过,解决pyinstaller打包exe文件出现命令窗口一闪而过的问题...
- VC6.0创建文件夹
- 2020中软java面试题,通过这9个Java面试题,就可以入职华为啦
- BUG报告:habahaba风格,图片显示有问题
- CTFHUB WEB
- taskctl控制容器之定时器个人理解
- 官网下载Windos10正版镜像并安装
- 用U盘安装Windows系统操作步骤
- linux终端下如何下载文件,Linux终端下载文件的方法有哪些?
- python实现两个word文档对比
- TeamViewer远程控制软件的许可证有什么用处
- 漫画 | 为什么程序猿996会猝死,而企业家007却不会?
- 使对话框的最大化、最小化和关闭按钮变灰以及对其重载的方法
热门文章
- numa节点_NUMA架构下的内存访问延迟区别!
- Unity URP一分钟实现遮挡透视
- double float区别 java,float和double有什么区别?
- OpenShift 4 - 使用Prometheus监控Node节点
- Jupyter.net:使用Jupyter进行交互式计算的Windows应用程序
- Linus 将 Linux 的软盘驱动 floppy 标记为“孤立”状态
- 计算机应用基础10000字论文,计算机应用毕业设计论文一万字.docx
- kdump需要开启吗_iPhone全新黑科技!用嘴玩手机!你会玩吗?
- js 滚动条自动滚动到最底部
- gradle 不支持多级子模块_解决gradle多模块依赖在Idea中能运行,gradle build失败的问题。...