前言

现在发送邮件是一个网站必备的功能,比如注册激活,或者忘记密码等等都需要发送邮件。正常我们会用JavaMail相关api来写发送邮件的相关代码,但现在springboot提供了一套更简易使用的封装。也就是我们使用SpringBoot来发送邮件的话,代码就简单许多,毕竟SpringBoot是开箱即用的 ,它提供了什么,我们了解之后觉得可行,就使用它,自己没必要再写原生的。

实践

导入依赖pom.xml

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置发送方信息

我们需要在SpringBoot配置文件(application.yml)中配置发送方的信息,包括以下信息:

用户名:也就是我们的邮箱账号
密码:我们刚刚生成的授权码
邮箱主机:配置使用哪个邮箱服务器发送邮件
还有等等其他可选配置,在下面配置代码中,大家需要填写自己的用户名、密码、from(和用户名一样)。

spring:mail:host: mail.xxxx.com#发送邮件的邮箱地址username: hadoop#客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的password: a5veproperties.mail.smtp.port: 587 #端口号465或587from: hadoop@xxx.com  # 发送邮件的地址,和上面username一致default-encoding: utf-8# 收件人 这个是自定义的to: xxx@xxx.com, op@xxx.com

MailDO

public class MailDO {/*** 标题*/private String title;/*** 内容*/private String content;/*** 接收人邮箱*/private String[] email;/*** 附加,value 文件的绝对地址/动态模板数据*/private Map<String, Object> attachment;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String[] getEmail() {return email;}public void setEmail(String[] email) {this.email = email;}public Map<String, Object> getAttachment() {return attachment;}public void setAttachment(Map<String, Object> attachment) {this.attachment = attachment;}@Overridepublic String toString() {return "MailDO{" +"title='" + title + '\'' +", content='" + content + '\'' +", email=" + Arrays.toString(email) +", attachment=" + attachment +'}';}
}

EmailService

我们需要自己封装邮件服务,这个服务只是便于Controller层调用,也就是根据客户端发送的请求来调用,封装三种邮件服务

  • 发送普通文本邮件
  • 发送HTML邮件:一般在注册激活时使用
  • 发送带附件的邮件:可以发送图片等等附件
public interface EmailService {/*** 发送* @param mailDO*/void sendTextMail(MailDO mailDO);/*** 发送html邮件* @param mailDO* @param isShowHtml*/void sendHtmlMail(MailDO mailDO,boolean isShowHtml);/*** 发送Template邮件* @param mailDO*/void sendTemplateMail(MailDO mailDO);
}

EmailServiceImpl

@Service
public class EmailServiceImpl implements EmailService {private final static Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);//template模板引擎@Autowiredprivate TemplateEngine templateEngine;@Autowiredprivate JavaMailSender javaMailSender;@Value("${spring.mail.from}")private String from;/*** 纯文本邮件* @param mail*/@Async@Overridepublic void sendTextMail(MailDO mail){//建立邮件消息SimpleMailMessage message = new SimpleMailMessage();// 发送人的邮箱message.setFrom(from);//标题message.setSubject(mail.getTitle());//发给谁  对方邮箱message.setTo(mail.getEmail());//内容message.setText(mail.getContent());try {//发送javaMailSender.send(message);} catch (MailException e) {log.error("纯文本邮件发送失败->message:{}",e.getMessage());throw new RuntimeException("邮件发送失败");}}/*** 发送的邮件是富文本(附件,图片,html等)* @param mailDO* @param isShowHtml 是否解析html*/@Async@Overridepublic void sendHtmlMail(MailDO mailDO, boolean isShowHtml) {try {MimeMessage mimeMessage = javaMailSender.createMimeMessage();//是否发送的邮件是富文本(附件,图片,html等)MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);messageHelper.setFrom(from);// 发送人的邮箱messageHelper.setTo(mailDO.getEmail());//发给谁  对方邮箱messageHelper.setSubject(mailDO.getTitle());//标题messageHelper.setText(mailDO.getContent(),isShowHtml);//false,显示原始html代码,无效果//判断是否有附加图片等if(mailDO.getAttachment() != null && mailDO.getAttachment().size() > 0){mailDO.getAttachment().entrySet().stream().forEach(entrySet -> {try {File file = new File(String.valueOf(entrySet.getValue()));if(file.exists()){messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));}} catch (MessagingException e) {log.error("附件发送失败->message:{}",e.getMessage());throw new RuntimeException("附件发送失败");}});}//发送javaMailSender.send(mimeMessage);log.info("富文本邮件发送成功,from: {}, to: {}",from,mailDO.getEmail());} catch (MessagingException e) {log.error("富文本邮件发送失败->message:{}",e.getMessage());throw new RuntimeException("邮件发送失败");}}/*** 发送模板邮件 使用thymeleaf模板* 若果使用freemarker模板*     Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);*     configuration.setClassForTemplateLoading(this.getClass(), "/templates");*     String emailContent = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);* @param mailDO*/@Async@Overridepublic void sendTemplateMail(MailDO mailDO) {try {MimeMessage mimeMessage = javaMailSender.createMimeMessage();MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);// 发送人的邮箱messageHelper.setFrom(from);//发给谁  对方邮箱messageHelper.setTo(mailDO.getEmail());//标题messageHelper.setSubject(mailDO.getTitle());//使用模板thymeleaf//Context是导这个包import org.thymeleaf.context.Context;Context context = new Context();//定义模板数据context.setVariables(mailDO.getAttachment());//获取thymeleaf的html模板String emailContent = templateEngine.process("indexPatternMail.html",context); //指定模板路径messageHelper.setText(emailContent,true);//发送邮件javaMailSender.send(mimeMessage);} catch (MessagingException e) {log.error("模板邮件发送失败->message:{}",e.getMessage());throw new RuntimeException("邮件发送失败");}}
}

模板 mail.html

放在templates/mail目录下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>title</title>
</head>
<body><h3>你看我<span style="font-size: 35px" th:text="${username}"></span>, 哈哈哈!</h3>
</body>
</html>

【springboot】springboot发送email(文本/html格式)邮件相关推荐

  1. 通过C#发送自定义的html格式邮件

    通过C#发送邮件,可以根据自己的需求更改. 这个是个配置文件的类,可以用,也可以改,也可以不用. using System; using System.IO; using System.Runtime ...

  2. php 读取邮件内容,PHP Mail:使用纯文本和HTML格式发送Email(多部分消息)

    使用PHP Mail发送邮件,可以选择纯文本格式或者HTML格式,HTML格式更加吸引眼球因此应用越来越广泛,但使用HTML格式有一定的劣势[1],在发送HTML格式的邮件时最好同时发送纯文本格式,这 ...

  3. Springboot发送Email

    Springboot发送Email 准备的东西 https://mail.163.com/ 邮箱 需要开通 POP3/SMTP/IMAP服务 163邮箱开通协议->设置->左侧 POP3/ ...

  4. qq邮箱发送html文本,使用qq邮箱发送html格式的邮件

    import smtplib from email.mime.text import MIMEText mailto_list=["[email protected]"," ...

  5. SpringBoot实现发送QQ邮箱验证码

    SpringBoot实现发送QQ邮箱验证码 打开qq邮箱官网 点击设置 找到开启服务:POP3/SMTP 然后复制给的密授权码(记住) 导入maven依赖坐标 <!--qq邮箱--> &l ...

  6. 应用层之E-mail服务及javaMail邮件发送的知识总结

    关于Email服务你需要知道的知识点: 概述: 今天来介绍一下应用层的电子邮件服务,我们每天几乎都在用,电子邮件(email)服务也是一种基于C/S模式的服务,它采用的是一种"存储-转发&q ...

  7. 使用Python内置的smtplib包和email包来实现邮件的构造和发送

    Python_sendEmail 使用Python内置的smtplib包和email包来实现邮件的构造和发送. 发送纯文本时: 1.需要导入Python3标准库中的smtplib包和email包来实现 ...

  8. .net 发送html邮件,c#利用system.net发送html格式邮件

    using system; using system.text; using system.net; using system.net.mail; using system.net.mime; nam ...

  9. python3邮件_python3使用SMTP发送简单文本邮件

    一.设置开启SMTP服务并获取授权码 0.如果使用第三方邮件服务器SMTP服务来发送邮件,首先要在邮箱设置里面开启POP3/SMTP/IMAP服务,下面以163邮箱为例,其它邮箱设置方法相同 163邮 ...

最新文章

  1. yum 快速搭建lnmp环境
  2. java中sum=a+aa+aaa_Java面向对象基础IO系统
  3. 047_输出一下byte的所有值
  4. Linux自带iscsi-target使用
  5. 三年程序员之后的思考
  6. jquery 里面对数组去重操作-unique
  7. 计算机应用12班,计算机应用二班xx毕业论文.doc
  8. 黑马程序员——java基础---多线程(二)
  9. Git工作流指南:集中式工作流
  10. ASP.NET Core(十)Configuration 配置优先级详解
  11. 探索 .NET Core 依赖注入的 IServiceProvider
  12. linux查服务器总内存大小,在linux 下怎么查看服务器的cpu和内存的硬件信息
  13. Weka--Explorer基本流程
  14. imdisk虚拟光驱安装linux,ImDisk Virtual Disk Driver
  15. 德鲁克对管理学的贡献
  16. CF卡 本地磁盘模式转换
  17. 关于 pace 有意思的一篇文章
  18. 直方图均衡(HE)与局部色调映射(LTM)
  19. R语言分组画条形图——qplot
  20. 基于ASP.NET的电商系统的设计与实现

热门文章

  1. 九巨龙物业拾金不昧,专业服务被点赞
  2. Android开发调试无法连接到夜神模拟器的解决方法
  3. python实现截图操作(android、PC、批处理)
  4. position:sticky;粘性布局
  5. iphone手机充电口耳机孔接触不良
  6. H5实现类蚂蚁森林动态气泡的渲染与收集
  7. Python实现VRP常见求解算法——差分进化算法(DE)
  8. ReverseFind(‘//’)函数并不是得到从右开始到//的字节数
  9. Android重力感应 .
  10. 【安卓开发】安卓页面跳转