SpringBoot 2.x 集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件
在Spring中提供了非常好用的 JavaMailSender接口实现邮件发送,在SpringBoot的Starter模块中也为此提供了自动化配置。
项目源码已托管在Gitee-SpringBoot_Guide
几个名词解释
Spring Boot中发送邮件步骤
Spring Boot中发送邮件具体的使用步骤如下
- 1、添加Starter模块依赖
- 2、添加Spring Boot配置(QQ/网易系/Gmail)
- 3、调用JavaMailSender接口发送邮件
添加Starter模块依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
添加Spring Boot配置
在application.yml中添加邮件相关的配置,这里分别罗列几个常用邮件的配置比如QQ邮箱、网易系邮箱、Gmail邮箱。
QQ邮箱配置
官方配置说明:参考官方帮助中心
获取客户端授权码:参考官方帮助中心
详细的配置如下:
spring:
mail:
host: smtp.qq.com #发送邮件服务器
username: xx@qq.com #QQ邮箱
password: xxxxxxxxxxx #客户端授权码
protocol: smtp #发送邮件协议
properties.mail.smtp.auth: true
properties.mail.smtp.port: 465 #端口号465或587
properties.mail.display.sendmail: Javen #可以任意
properties.mail.display.sendname: Spring Boot Guide Email #可以任意
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
from: xx@qq.com #与上面的username保持一致
说明:开启SSL时使用587端口时无法连接QQ邮件服务器
网易系(126/163/yeah)邮箱配置
网易邮箱客户端授码:参考官方帮助中心
客户端端口配置说明:参考官方帮助中心
详细的配置如下:
spring:
mail:
host: smtp.126.com
username: xx@126.com
password: xxxxxxxx
protocol: smtp
properties.mail.smtp.auth: true
properties.mail.smtp.port: 994 #465或者994
properties.mail.display.sendmail: Javen
properties.mail.display.sendname: Spring Boot Guide Email
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
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
的异常
选择登录与安全滑到底部有个允许不够安全的应用
开启即可
详细的配置如下:
spring:
mail:
host: smtp.gmail.com
username:xxx@gmail.com
password: xxxxx #Gmail账号密码
protocol: smtp
properties.mail.smtp.auth: true
properties.mail.smtp.port: 465
properties.mail.display.sendmail: Javen
properties.mail.display.sendname: Spring Boot Guide Email
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
from: xxx@gmail.com
default-encoding: utf-8
调用JavaMailSender接口发送邮件
常用几种邮件形式接口的封装
import javax.mail.MessagingException;
public interface IMailService {
/**
* 发送文本邮件
* @param to
* @param subject
* @param content
*/
public void sendSimpleMail(String to, String subject, String content);
public void sendSimpleMail(String to, String subject, String content, String... cc);
/**
* 发送HTML邮件
* @param to
* @param subject
* @param content
* @throws MessagingException
*/
public void sendHtmlMail(String to, String subject, String content) throws MessagingException;
public void sendHtmlMail(String to, String subject, String content, String... cc);
/**
* 发送带附件的邮件
* @param to
* @param subject
* @param content
* @param filePath
* @throws MessagingException
*/
public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException;
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc);
/**
* 发送正文中有静态资源的邮件
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId
* @throws MessagingException
*/
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException;
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc);
}
再写一个组件实现上面的接口并注入JavaMailSender
@Component
public class IMailServiceImpl implements IMailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.from}")
private String from;
//具体实现请继续向下阅读
}
发送文本邮件
/**
* 发送文本邮件
* @param to
* @param subject
* @param content
*/
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
@Override
public void sendSimpleMail(String to, String subject, String content, String... cc) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setCc(cc);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
发送html邮件
/**
* 发送HTML邮件
* @param to
* @param subject
* @param content
*/
@Override
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
}
省略实现带有抄送方法的实现
发送带附件的邮件
/**
* 发送带附件的邮件
* @param to
* @param subject
* @param content
* @param filePath
*/
public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
mailSender.send(message);
}
省略实现带有抄送方法的实现
发送正文中有静态资源的邮件
/**
* 发送正文中有静态资源的邮件
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId
*/
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
}
省略实现带有抄送方法的实现
发送模板邮件
发送模板邮件使用的方法与发送HTML邮件的方法一致。只是发送邮件时使用到的模板引擎,这里使用的模板引擎为Thymeleaf
。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
模板HTML代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>IJPay让支付触手可及</title>
<style>
body {
text-align: center;
margin-left: auto;
margin-right: auto;
}
#welcome {
text-align: center;
position: absolute;
}
</style>
</head>
<body>
<div id="welcome">
<h3>欢迎使用 <span th:text="${project}"></span> -By <span th:text=" ${author}"></span></h3>
<span th:text="${url}"></span>
<div style="text-align: center; padding: 10px">
<a style="text-decoration: none;" href="#" th:href="@{${url}}" target="_bank">
<strong>IJPay让支付触手可及,欢迎Start支持项目发展:)</strong>
</a>
</div>
<div style="text-align: center; padding: 4px">
如果对你有帮助,请任意打赏
</div>
<img width="180px" height="180px"
src="https://oscimg.oschina.net/oscnet/8e86fed2ee9571eb133096d5dc1b3cb2fc1.jpg">
</div>
</body>
</html>
如何使用请看测试中实现的代码。
测试
package com.javen.controller;
import com.javen.email.impl.IMailServiceImpl;
import com.javen.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@RestController
@RequestMapping("email")
public class EmailController {
@Autowired
private IMailServiceImpl mailService;//注入发送邮件的各种实现方法
@Autowired
private TemplateEngine templateEngine;//注入模板引擎
@RequestMapping
public JsonResult index(){
try {
mailService.sendSimpleMail("xxx@126.com","SpringBoot Email","这是一封普通的SpringBoot测试邮件");
}catch (Exception ex){
ex.printStackTrace();
return new JsonResult(-1,"邮件发送失败!!");
}
return new JsonResult();
}
@RequestMapping("/htmlEmail")
public JsonResult htmlEmail(){
try {
mailService.sendHtmlMail(""xxx@126.com","IJPay让支付触手可及","<body style=\"text-align: center;margin-left: auto;margin-right: auto;\">\n"
+ " <div id=\"welcome\" style=\"text-align: center;position: absolute;\" >\n"
+" <h3>欢迎使用IJPay -By Javen</h3>\n"
+" <span>https://github.com/Javen205/IJPay</span>"
+ " <div\n"
+ " 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"
+ " <div\n" + " style=\"text-align: center; padding: 4px\">如果对你有帮助,请任意打赏</div>\n"
+ " <img width=\"180px\" height=\"180px\"\n"
+ " src=\"https://javen205.gitbooks.io/ijpay/content/assets/wxpay.png\">\n"
+ " </div>\n" + "</body>");
}catch (Exception ex){
ex.printStackTrace();
return new JsonResult(-1,"邮件发送失败!!");
}
return new JsonResult();
}
@RequestMapping("/attachmentsMail")
public JsonResult attachmentsMail(){
try {
String filePath = "/Users/Javen/Desktop/IJPay.png";
mailService.sendAttachmentsMail("xxx@126.com", "这是一封带附件的邮件", "邮件中有附件,请注意查收!", filePath);
}catch (Exception ex){
ex.printStackTrace();
return new JsonResult(-1,"邮件发送失败!!");
}
return new JsonResult();
}
@RequestMapping("/resourceMail")
public JsonResult resourceMail(){
try {
String rscId = "IJPay";
String content = "<html><body>这是有图片的邮件<br/><img src=\'cid:" + rscId + "\' ></body></html>";
String imgPath = "/Users/Javen/Desktop/IJPay.png";
mailService.sendResourceMail("xxx@126.com", "这邮件中含有图片", content, imgPath, rscId);
}catch (Exception ex){
ex.printStackTrace();
return new JsonResult(-1,"邮件发送失败!!");
}
return new JsonResult();
}
@RequestMapping("/templateMail")
public JsonResult templateMail(){
try {
Context context = new Context();
context.setVariable("project", "IJPay");
context.setVariable("author", "Javen");
context.setVariable("url", "https://github.com/Javen205/IJPay");
String emailContent = templateEngine.process("emailTemp", context);
mailService.sendHtmlMail("xxx@126.com", "这是模板邮件", emailContent);
}catch (Exception ex){
ex.printStackTrace();
return new JsonResult(-1,"邮件发送失败!!");
}
return new JsonResult();
}
}
效果图
[
源码下载
项目源码已托管在Gitee-SpringBoot_Guide
如果对你有帮助请点击博客下的推荐,欢迎转发
完
使用 Spring Boot 发送邮件到这里就介绍完了。个人能力有限如有错误欢迎指正。你有更好的解决方案或者建议欢迎一起交流讨论,如有疑问欢迎留言。
SpringBoot 2.x 集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件的更多相关文章
- 使用Gmail邮箱
由于国内不能直接访问google,所以其相关产品也不能直接使用.因为Gmail简洁,使用方便,国际上用的人很多.最近发现网易邮箱大师可以直接访问Gmail,所以将方法介绍给大家,如果大家只有访问Gma ...
- Springboot】Springboot整合邮件服务(HTML/附件/模板-QQ、网易)
介绍 邮件服务是常用的服务之一,作用很多,对外可以给用户发送活动.营销广告等:对内可以发送系统监控报告与告警. 本文将介绍Springboot如何整合邮件服务,并给出不同邮件服务商的整合配置. 如图所 ...
- 在foxmail和outlook中设置QQ邮箱、gmail邮箱、新浪邮箱、微软邮箱、网易邮箱等的方法
怎么用邮件客户端如outlook和foxmail来设置各种邮箱 很多人平时都是在网页上面收发邮件,这个很简单,不用其他的设置,不过在客户端上设置收发邮件还是很不错的,今天就来讲讲各种邮箱在outloo ...
- 十二、SpringBoot 优雅的集成Spring Security
前言 至于什么是Spring security ,主要两个作用,用户认证和授权.即我们常说的,用户只有登录了才能进行其他操作,没有登录的话就重定向到登录界面.有的用户有权限执行某一操作,而有的用户不能 ...
- 网站集成QQ登录功能
最近在做一个项目时,客户要求网站能够集成QQ登录的功能,以前没做过这方面的开发,于是去QQ的开放平台官网研究了一下相关资料,经过自己的艰苦探索,终于实现了集成QQ登录的功能,现在把相关的开发经验总结一 ...
- 友盟分享--集成QQ和微信
随着社交工具的应用范围越来越广,分享一些内容的功能也开始要求实现了. 用得比较多的第三方,比如说友盟,比如说Share等等... 前几天刚用友盟写了集成QQ和微信客户端的功能,觉得有必要分享一下. 在 ...
- C#发送Email邮件(实例:QQ邮箱和Gmail邮箱)
下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需要引用: using System.Net.Mail; using System.Text; using System.Net; ...
- [转]C#发送Email邮件 (实例:QQ邮箱和Gmail邮箱)
下面用到的邮件账号和密码都不是真实的,需要测试就换成自己的邮件账号. 需要引用:using System.Net.Mail;using System.Text;using System.Net; 程序 ...
- 网站集成QQ登录功能(转)
最近在做一个项目时,客户要求网站能够集成QQ登录的功能,以前没做过这方面的开发,于是去QQ的开放平台官网研究了一下相关资料,经过自己的艰苦探索,终于实现了集成QQ登录的功能,现在把相关的开发经验总结一 ...
随机推荐
- python--模拟蜂窝网(https)登陆总结
#用户名密码登陆 1.寻找登陆请求(此处可以故意输错用户名密码,目的是为了能够看清楚重定向的地址) 发现: 点击登陆时,请求了 ①.post302:https://passport.mafengwo. ...
- NOIP2017提高组Day1T3 逛公园 洛谷P3953 Tarjan 强连通缩点 SPFA 动态规划 最短路 拓扑序
原文链接https://www.cnblogs.com/zhouzhendong/p/9258043.html 题目传送门 - 洛谷P3953 题目传送门 - Vijos P2030 题意 给定一个有 ...
- springboot学习——第二集:整合Mybaits
1,Mybatis动态插入(insert)数据(使用trim标签):https://blog.csdn.net/h12kjgj/article/details/55003713 2,mybatis 中 ...
- 064 SparkStream与kafka的集成,主要是编程
这里面包含了如何在kafka+sparkStreaming集成后的开发,也包含了一部分的优化. 一:说明 1.官网 指导网址:http://spark.apache.org/docs/1.6.1/st ...
- IntelliJ IDEA 插件 阿里巴巴Java开发手册(Alibaba Java Coding Guidelines)
以前看到过个:Java开发手册(阿里巴巴-公开版),这是个pdf文档,里面描述了一些Java开发的规约,里面确实有很多好用的规约,要是在学校就有机会看看的话,那么,在毕业之后,实际工作中就会少很多坑. ...
- java中path和CLASSPATH的配置和意义解析
原文链接 https://blog.csdn.net/eclipse_yin/article/details/51447169 一.JDK的安装和基本配置 JDK的安装: 1) 如果想要获得JDK,那 ...
- POJ 3258 River Hopscotch (最大最小距离)【二分】
<题目链接> 题目大意:现在有起点和终点两个石块,这两个石块之间有N个石块,现在对这N个石块移除M个石块,使得这些石块之间的最短距离最大,注意,起点和终点这两个石块不能被移除. 解题分析: ...
- Linux命令集
系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...
- Effective前端2---加快页面打开速度
1.避免head标签JS阻塞 所有放在head标签里的JS和CSS都会阻塞页面渲染.如果这些CSS和JS需要记在时间比较久,中间页面会存在一个空白期,严重影响到用户体验. 例如以下代码:在head标签 ...
- 说说nginx,iis,apache,tomcat
一.nginx ngnix是反向代理服务器,它是代理,本身并不执行,是个传话筒,把用户提交的请求转发给web服务器,再把web服务器的结果转发给用户.为了提高性能,启用反向代理,实际的web服务器可以 ...