在Spring中提供了非常好用的 JavaMailSender接口实现邮件发送,在SpringBoot的Starter模块中也为此提供了自动化配置。

项目源码已托管在Gitee-SpringBoot_Guide

几个名词解释

Spring Boot中发送邮件步骤

Spring Boot中发送邮件具体的使用步骤如下

  • 1、添加Starter模块依赖
  • 2、添加Spring Boot配置(QQ/网易系/Gmail)
  • 3、调用JavaMailSender接口发送邮件

添加Starter模块依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-mail</artifactId>
  4. </dependency>

添加Spring Boot配置

application.yml中添加邮件相关的配置,这里分别罗列几个常用邮件的配置比如QQ邮箱、网易系邮箱、Gmail邮箱。

QQ邮箱配置

官方配置说明:参考官方帮助中心

获取客户端授权码:参考官方帮助中心

详细的配置如下:

  1. spring:
  2. mail:
  3. host: smtp.qq.com #发送邮件服务器
  4. username: xx@qq.com #QQ邮箱
  5. password: xxxxxxxxxxx #客户端授权码
  6. protocol: smtp #发送邮件协议
  7. properties.mail.smtp.auth: true
  8. properties.mail.smtp.port: 465 #端口号465或587
  9. properties.mail.display.sendmail: Javen #可以任意
  10. properties.mail.display.sendname: Spring Boot Guide Email #可以任意
  11. properties.mail.smtp.starttls.enable: true
  12. properties.mail.smtp.starttls.required: true
  13. properties.mail.smtp.ssl.enable: true
  14. default-encoding: utf-8
  15. from: xx@qq.com #与上面的username保持一致

说明:开启SSL时使用587端口时无法连接QQ邮件服务器

网易系(126/163/yeah)邮箱配置

网易邮箱客户端授码:参考官方帮助中心

客户端端口配置说明:参考官方帮助中心

详细的配置如下:

  1. spring:
  2. mail:
  3. host: smtp.126.com
  4. username: xx@126.com
  5. password: xxxxxxxx
  6. protocol: smtp
  7. properties.mail.smtp.auth: true
  8. properties.mail.smtp.port: 994 #465或者994
  9. properties.mail.display.sendmail: Javen
  10. properties.mail.display.sendname: Spring Boot Guide Email
  11. properties.mail.smtp.starttls.enable: true
  12. properties.mail.smtp.starttls.required: true
  13. properties.mail.smtp.ssl.enable: true
  14. default-encoding: utf-8
  15. from: xx@126.com

特别说明:

  • 126邮箱SMTP服务器地址:smtp.126.com,端口号:465或者994
  • 163邮箱SMTP服务器地址:smtp.163.com,端口号:465或者994
  • yeah邮箱SMTP服务器地址:smtp.yeah.net,端口号:465或者994
Gmail邮箱配置

Gmail 客户端设置说明:参考官方Gmail帮助

以上链接需要自行搭梯子,这里截几张图参考下





总结:

Gmail 发送邮件服务器为:smtp.gmail.com,端口号:465。客户端授权码为Gmail账号的密码,必须使用使用SSL。

还需要开启允许不够安全的应用 ,不然会出现Authentication failed的异常

选择登录与安全滑到底部有个允许不够安全的应用开启即可

详细的配置如下:

  1. spring:
  2. mail:
  3. host: smtp.gmail.com
  4. username:xxx@gmail.com
  5. password: xxxxx #Gmail账号密码
  6. protocol: smtp
  7. properties.mail.smtp.auth: true
  8. properties.mail.smtp.port: 465
  9. properties.mail.display.sendmail: Javen
  10. properties.mail.display.sendname: Spring Boot Guide Email
  11. properties.mail.smtp.starttls.enable: true
  12. properties.mail.smtp.starttls.required: true
  13. properties.mail.smtp.ssl.enable: true
  14. from: xxx@gmail.com
  15. default-encoding: utf-8

调用JavaMailSender接口发送邮件

常用几种邮件形式接口的封装

  1. import javax.mail.MessagingException;
  2. public interface IMailService {
  3. /**
  4. * 发送文本邮件
  5. * @param to
  6. * @param subject
  7. * @param content
  8. */
  9. public void sendSimpleMail(String to, String subject, String content);
  10. public void sendSimpleMail(String to, String subject, String content, String... cc);
  11. /**
  12. * 发送HTML邮件
  13. * @param to
  14. * @param subject
  15. * @param content
  16. * @throws MessagingException
  17. */
  18. public void sendHtmlMail(String to, String subject, String content) throws MessagingException;
  19. public void sendHtmlMail(String to, String subject, String content, String... cc);
  20. /**
  21. * 发送带附件的邮件
  22. * @param to
  23. * @param subject
  24. * @param content
  25. * @param filePath
  26. * @throws MessagingException
  27. */
  28. public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException;
  29. public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc);
  30. /**
  31. * 发送正文中有静态资源的邮件
  32. * @param to
  33. * @param subject
  34. * @param content
  35. * @param rscPath
  36. * @param rscId
  37. * @throws MessagingException
  38. */
  39. public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException;
  40. public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc);
  41. }

再写一个组件实现上面的接口并注入JavaMailSender

  1. @Component
  2. public class IMailServiceImpl implements IMailService {
  3. @Autowired
  4. private JavaMailSender mailSender;
  5. @Value("${spring.mail.from}")
  6. private String from;
  7. //具体实现请继续向下阅读
  8. }
发送文本邮件
  1. /**
  2. * 发送文本邮件
  3. * @param to
  4. * @param subject
  5. * @param content
  6. */
  7. @Override
  8. public void sendSimpleMail(String to, String subject, String content) {
  9. SimpleMailMessage message = new SimpleMailMessage();
  10. message.setFrom(from);
  11. message.setTo(to);
  12. message.setSubject(subject);
  13. message.setText(content);
  14. mailSender.send(message);
  15. }
  16. @Override
  17. public void sendSimpleMail(String to, String subject, String content, String... cc) {
  18. SimpleMailMessage message = new SimpleMailMessage();
  19. message.setFrom(from);
  20. message.setTo(to);
  21. message.setCc(cc);
  22. message.setSubject(subject);
  23. message.setText(content);
  24. mailSender.send(message);
  25. }
发送html邮件
  1. /**
  2. * 发送HTML邮件
  3. * @param to
  4. * @param subject
  5. * @param content
  6. */
  7. @Override
  8. public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
  9. MimeMessage message = mailSender.createMimeMessage();
  10. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  11. helper.setFrom(from);
  12. helper.setTo(to);
  13. helper.setSubject(subject);
  14. helper.setText(content, true);
  15. mailSender.send(message);
  16. }

省略实现带有抄送方法的实现

发送带附件的邮件
  1. /**
  2. * 发送带附件的邮件
  3. * @param to
  4. * @param subject
  5. * @param content
  6. * @param filePath
  7. */
  8. public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException {
  9. MimeMessage message = mailSender.createMimeMessage();
  10. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  11. helper.setFrom(from);
  12. helper.setTo(to);
  13. helper.setSubject(subject);
  14. helper.setText(content, true);
  15. FileSystemResource file = new FileSystemResource(new File(filePath));
  16. String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
  17. helper.addAttachment(fileName, file);
  18. mailSender.send(message);
  19. }

省略实现带有抄送方法的实现

发送正文中有静态资源的邮件
  1. /**
  2. * 发送正文中有静态资源的邮件
  3. * @param to
  4. * @param subject
  5. * @param content
  6. * @param rscPath
  7. * @param rscId
  8. */
  9. public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException {
  10. MimeMessage message = mailSender.createMimeMessage();
  11. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  12. helper.setFrom(from);
  13. helper.setTo(to);
  14. helper.setSubject(subject);
  15. helper.setText(content, true);
  16. FileSystemResource res = new FileSystemResource(new File(rscPath));
  17. helper.addInline(rscId, res);
  18. mailSender.send(message);
  19. }

省略实现带有抄送方法的实现

发送模板邮件

发送模板邮件使用的方法与发送HTML邮件的方法一致。只是发送邮件时使用到的模板引擎,这里使用的模板引擎为Thymeleaf

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. </dependency>

模板HTML代码如下:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>IJPay让支付触手可及</title>
  6. <style>
  7. body {
  8. text-align: center;
  9. margin-left: auto;
  10. margin-right: auto;
  11. }
  12. #welcome {
  13. text-align: center;
  14. position: absolute;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="welcome">
  20. <h3>欢迎使用 <span th:text="${project}"></span> -By <span th:text=" ${author}"></span></h3>
  21. <span th:text="${url}"></span>
  22. <div style="text-align: center; padding: 10px">
  23. <a style="text-decoration: none;" href="#" th:href="@{${url}}" target="_bank">
  24. <strong>IJPay让支付触手可及,欢迎Start支持项目发展:)</strong>
  25. </a>
  26. </div>
  27. <div style="text-align: center; padding: 4px">
  28. 如果对你有帮助,请任意打赏
  29. </div>
  30. <img width="180px" height="180px"
  31. src="https://oscimg.oschina.net/oscnet/8e86fed2ee9571eb133096d5dc1b3cb2fc1.jpg">
  32. </div>
  33. </body>
  34. </html>

如何使用请看测试中实现的代码。

测试


  1. package com.javen.controller;
  2. import com.javen.email.impl.IMailServiceImpl;
  3. import com.javen.vo.JsonResult;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import org.thymeleaf.TemplateEngine;
  8. import org.thymeleaf.context.Context;
  9. @RestController
  10. @RequestMapping("email")
  11. public class EmailController {
  12. @Autowired
  13. private IMailServiceImpl mailService;//注入发送邮件的各种实现方法
  14. @Autowired
  15. private TemplateEngine templateEngine;//注入模板引擎
  16. @RequestMapping
  17. public JsonResult index(){
  18. try {
  19. mailService.sendSimpleMail("xxx@126.com","SpringBoot Email","这是一封普通的SpringBoot测试邮件");
  20. }catch (Exception ex){
  21. ex.printStackTrace();
  22. return new JsonResult(-1,"邮件发送失败!!");
  23. }
  24. return new JsonResult();
  25. }
  26. @RequestMapping("/htmlEmail")
  27. public JsonResult htmlEmail(){
  28. try {
  29. mailService.sendHtmlMail(""xxx@126.com","IJPay让支付触手可及","<body style=\"text-align: center;margin-left: auto;margin-right: auto;\">\n"
  30. + " <div id=\"welcome\" style=\"text-align: center;position: absolute;\" >\n"
  31. +" <h3>欢迎使用IJPay -By Javen</h3>\n"
  32. +" <span>https://github.com/Javen205/IJPay</span>"
  33. + " <div\n"
  34. + " style=\"text-align: center; padding: 10px\"><a style=\"text-decoration: none;\" href=\"https://github.com/Javen205/IJPay\" target=\"_bank\" ><strong>IJPay 让支付触手可及,欢迎Start支持项目发展:)</strong></a></div>\n"
  35. + " <div\n" + " style=\"text-align: center; padding: 4px\">如果对你有帮助,请任意打赏</div>\n"
  36. + " <img width=\"180px\" height=\"180px\"\n"
  37. + " src=\"https://javen205.gitbooks.io/ijpay/content/assets/wxpay.png\">\n"
  38. + " </div>\n" + "</body>");
  39. }catch (Exception ex){
  40. ex.printStackTrace();
  41. return new JsonResult(-1,"邮件发送失败!!");
  42. }
  43. return new JsonResult();
  44. }
  45. @RequestMapping("/attachmentsMail")
  46. public JsonResult attachmentsMail(){
  47. try {
  48. String filePath = "/Users/Javen/Desktop/IJPay.png";
  49. mailService.sendAttachmentsMail("xxx@126.com", "这是一封带附件的邮件", "邮件中有附件,请注意查收!", filePath);
  50. }catch (Exception ex){
  51. ex.printStackTrace();
  52. return new JsonResult(-1,"邮件发送失败!!");
  53. }
  54. return new JsonResult();
  55. }
  56. @RequestMapping("/resourceMail")
  57. public JsonResult resourceMail(){
  58. try {
  59. String rscId = "IJPay";
  60. String content = "<html><body>这是有图片的邮件<br/><img src=\'cid:" + rscId + "\' ></body></html>";
  61. String imgPath = "/Users/Javen/Desktop/IJPay.png";
  62. mailService.sendResourceMail("xxx@126.com", "这邮件中含有图片", content, imgPath, rscId);
  63. }catch (Exception ex){
  64. ex.printStackTrace();
  65. return new JsonResult(-1,"邮件发送失败!!");
  66. }
  67. return new JsonResult();
  68. }
  69. @RequestMapping("/templateMail")
  70. public JsonResult templateMail(){
  71. try {
  72. Context context = new Context();
  73. context.setVariable("project", "IJPay");
  74. context.setVariable("author", "Javen");
  75. context.setVariable("url", "https://github.com/Javen205/IJPay");
  76. String emailContent = templateEngine.process("emailTemp", context);
  77. mailService.sendHtmlMail("xxx@126.com", "这是模板邮件", emailContent);
  78. }catch (Exception ex){
  79. ex.printStackTrace();
  80. return new JsonResult(-1,"邮件发送失败!!");
  81. }
  82. return new JsonResult();
  83. }
  84. }

效果图

[









源码下载

项目源码已托管在Gitee-SpringBoot_Guide

如果对你有帮助请点击博客下的推荐,欢迎转发

使用 Spring Boot 发送邮件到这里就介绍完了。个人能力有限如有错误欢迎指正。你有更好的解决方案或者建议欢迎一起交流讨论,如有疑问欢迎留言。

参考资料

SpringBoot 2.x 集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件的更多相关文章

  1. 使用Gmail邮箱

    由于国内不能直接访问google,所以其相关产品也不能直接使用.因为Gmail简洁,使用方便,国际上用的人很多.最近发现网易邮箱大师可以直接访问Gmail,所以将方法介绍给大家,如果大家只有访问Gma ...

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

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

  3. 在foxmail和outlook中设置QQ邮箱、gmail邮箱、新浪邮箱、微软邮箱、网易邮箱等的方法

    怎么用邮件客户端如outlook和foxmail来设置各种邮箱 很多人平时都是在网页上面收发邮件,这个很简单,不用其他的设置,不过在客户端上设置收发邮件还是很不错的,今天就来讲讲各种邮箱在outloo ...

  4. 十二、SpringBoot 优雅的集成Spring Security

    前言 至于什么是Spring security ,主要两个作用,用户认证和授权.即我们常说的,用户只有登录了才能进行其他操作,没有登录的话就重定向到登录界面.有的用户有权限执行某一操作,而有的用户不能 ...

  5. 网站集成QQ登录功能

    最近在做一个项目时,客户要求网站能够集成QQ登录的功能,以前没做过这方面的开发,于是去QQ的开放平台官网研究了一下相关资料,经过自己的艰苦探索,终于实现了集成QQ登录的功能,现在把相关的开发经验总结一 ...

  6. 友盟分享--集成QQ和微信

    随着社交工具的应用范围越来越广,分享一些内容的功能也开始要求实现了. 用得比较多的第三方,比如说友盟,比如说Share等等... 前几天刚用友盟写了集成QQ和微信客户端的功能,觉得有必要分享一下. 在 ...

  7. C#发送Email邮件(实例:QQ邮箱和Gmail邮箱)

    下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需要引用: using System.Net.Mail; using System.Text; using System.Net; ...

  8. [转]C#发送Email邮件 (实例:QQ邮箱和Gmail邮箱)

    下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需要引用:using System.Net.Mail;using System.Text;using System.Net; 程序 ...

  9. 网站集成QQ登录功能(转)

    最近在做一个项目时,客户要求网站能够集成QQ登录的功能,以前没做过这方面的开发,于是去QQ的开放平台官网研究了一下相关资料,经过自己的艰苦探索,终于实现了集成QQ登录的功能,现在把相关的开发经验总结一 ...

随机推荐

  1. Best Cow Fences POJ - 2018 (二分)

    Farmer John's farm consists of a long row of N (1 <= N <= 100,000)fields. Each field contains ...

  2. poj 3694 Network 【Tarjan】+【LCA】

    <题目链接> 题目大意: 给一个无向图,该图只有一个连通分量.然后查询q次,q < 1000, 求每次查询就增加一条边,求剩余桥的个数. 解题分析: 普通的做法就是在每加一条边后,都 ...

  3. Java内存管理-掌握类加载器的核心源码和设计模式(六)

    勿在流沙筑高台,出来混迟早要还的. 做一个积极的人 编码.改bug.提升自己 我有一个乐园,面向编程,春暖花开! 上一篇文章介绍了类加载器分类以及类加载器的双亲委派模型,让我们能够从整体上对类加载器有 ...

  4. Django 学习第七天——Django模型基础第二节

    User 是自己创建的模型类,等于数据库中的表 常用的查询方法: all():获取所有数据: User.objects.all() first():获取第一条数据: User.objects.firs ...

  5. C#Stopwatch的简单计时zz

    Stopwatch 类 命名空间:System.Diagnostics.Stopwatch 实例化:Stopwatch getTime=new Stopwatch(); 开始计时:getTime.St ...

  6. Django之auth组件

    Django自带的用户认证 我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统.此时我们需要实现包括用户注册.用户登录.用户认证.注销.修改密码等功能,这还真是个麻烦的事情呢. Djang ...

  7. SpringMVC的请求处理流程

  8. java里的基本数据类型和引用数据类型

    一.基本数据类型: byte:Java中最小的数据类型,在内存中占8位(bit),即1个字节,取值范围-128~127,默认值0 short:短整型,在内存中占16位,即2个字节,取值范围-32768 ...

  9. array中key所对应的value

    获取数组中的键对应的值 class Test{ public function index(){ $info = array( 'name' => 'daicr', 'age' => 24 ...

  10. Code signing is required for product type 'Application' in SDK 'iOS 11.4'

    查看链接: https://blog.csdn.net/Fantasy_Jun/article/details/78082359 处理方法: 将code signing identity设置为iOS ...