SpringBoot 2.x 集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件

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

项目源码已托管在Gitee-SpringBoot_Guide

几个名词解释

  • 什么是POP3、SMTP和IMAP?
    详细介绍-请移步至网易帮助文档

  • IMAP和POP3有什么区别?

    详细介绍-请移步至网易帮助文档

  • 什么是免费邮箱客户端授权码功能?

    详细介绍-请移步至网易帮助文档

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: trueproperties.mail.smtp.port: 465 #端口号465或587properties.mail.display.sendmail: Javen #可以任意properties.mail.display.sendname: Spring Boot Guide Email #可以任意properties.mail.smtp.starttls.enable: trueproperties.mail.smtp.starttls.required: trueproperties.mail.smtp.ssl.enable: truedefault-encoding: utf-8from: xx@qq.com #与上面的username保持一致

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

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

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

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

详细的配置如下:

spring:mail:host: smtp.126.comusername: xx@126.compassword: xxxxxxxxprotocol: smtpproperties.mail.smtp.auth: trueproperties.mail.smtp.port: 994 #465或者994properties.mail.display.sendmail: Javenproperties.mail.display.sendname: Spring Boot Guide Emailproperties.mail.smtp.starttls.enable: trueproperties.mail.smtp.starttls.required: trueproperties.mail.smtp.ssl.enable: truedefault-encoding: utf-8from: 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帮助

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

image
image
image

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

还需要开启允许不够安全的应用 ,不然会出现Authentication failed的异常
选择登录与安全滑到底部有个允许不够安全的应用开启即可

详细的配置如下:

spring:mail:host: smtp.gmail.comusername:xxx@gmail.compassword: xxxxx #Gmail账号密码protocol: smtpproperties.mail.smtp.auth: trueproperties.mail.smtp.port: 465properties.mail.display.sendmail: Javenproperties.mail.display.sendname: Spring Boot Guide Emailproperties.mail.smtp.starttls.enable: trueproperties.mail.smtp.starttls.required: trueproperties.mail.smtp.ssl.enable: truefrom: xxx@gmail.comdefault-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 {@Autowiredprivate JavaMailSender mailSender;@Value("${spring.mail.from}")private String from;//具体实现请继续向下阅读
}
发送文本邮件
 /*** 发送文本邮件* @param to* @param subject* @param content*/@Overridepublic 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);}@Overridepublic 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*/@Overridepublic 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 {@Autowiredprivate IMailServiceImpl mailService;//注入发送邮件的各种实现方法@Autowiredprivate TemplateEngine templateEngine;//注入模板引擎@RequestMappingpublic 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();}
}

效果图

[接收到的所有邮件
发送普通邮件
发送HTML邮件
发送带有附件的邮件
发送含有图片的邮件
发送模板邮件

源码下载

项目源码已托管在Gitee-SpringBoot_Guide 欢迎Start,如果对你有帮助请点击右上方的推荐/点赞同时欢迎转发

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

参考资料

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/1617825.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

Gmail配置邮箱客户端

公司的游戏的找回密码功能发邮件是走GMail渠道来实现的。之前在做这一部分的时候&#xff0c;受到QQ邮箱的影响&#xff0c;以为没什么大问题&#xff08;之前QQ邮箱配置过什么&#xff0c;也比较简单,简单设置好独立密码即可&#xff09;然后主要原因是这次再次经历了这个过程…

matlab 点云的二进制形状描述子

目录 一、功能概述1、算法概述2、主要函数3、参考文献二、代码示例三、结果展示四、参数解析输入参数名称-值对应参数输出参数五、参考链接本文由CSDN点云侠原创,

网易企业邮箱登录服务器出错,网易企业邮箱登录出现故障,无法正常登录

9月1日上午8:30左右&#xff0c;强比科技企业邮箱客服中心陆续接到网易企业邮箱用户反馈&#xff0c;在通过“mail.域名”登录邮箱过程中出现异常&#xff0c;页面出现“您所请求的网址(URL)无法获取”等错误提示&#xff0c;导致无法正常登录邮箱。 随后&#xff0c;客服人员进…

非常难得的iPad版房地产售楼助手应用

一款高质量的iPad房地产售楼助手应用&#xff0c;采用的是类似facebook&#xff0c;新浪微博&#xff0c;腾讯微博&#xff0c;人人网的布局视图。功能有&#xff1a;客户管理系统&#xff08;可添加&#xff0c;编辑等&#xff09;&#xff1b;2.房源管理系统;3.房贷计算器等&…

新IPAD安装程序

新IPAD安装程序 安装爱思助手iPad连接电脑复制UDID生成两个签名文件ipa签名安装制作好的ipa下拉设置服务器IP 安装爱思助手 https://www.i4.cn/ iPad连接电脑 复制UDID 生成两个签名文件 把复制的UDID发给研发或IT部&#xff0c;拿到生成的两个签名文件 ipa签名 安装制作…

linux并发服务器 —— Makefile与GDB调试(二)

Makefile Makefile&#xff1a;定义规则指定文件的编译顺序&#xff1b;类似shell脚本&#xff0c;执行操作系统命令 优点&#xff1a;自动化编译——通过make&#xff08;解释Makefile文件中指令的命令&#xff09;命令完全编译整个工程&#xff0c;提高软件开发效率&#x…

Windows下MATLAB调用Python函数操作说明

MATLAB与Python版本的兼容 具体可参看MATLAB与Python版本的兼容 操作说明 操作说明请参看下面两个链接&#xff1a; 操作指南 简单说明&#xff1a; 我安装的是MATLAB2022a和Python3.8.6&#xff08;安装时请勾选所有可以勾选的&#xff0c;包括路径&#xff09;。对应版本安…

Go测试之.golden 文件

Go测试中的.golden 文件是干什么用的&#xff1f;请举例说明 在Go语言中&#xff0c;.golden文件通常用于测试中的黄金文件&#xff08;golden files&#xff09;。黄金文件是在测试期间记录预期输出结果的文件。测试用例运行时&#xff0c;黄金文件用于比较实际输出与预期输出…

【js案例】滚动效果实现及简单动画函数抽离

目录 &#x1f31f;效果 &#x1f31f;实现思路 &#x1f31f;实现方法 HTML&CSS代码 初始化 滚动效果 完整JS代码 &#x1f31f;抽离动画函数 函数的简单使用 小案例一 小案例二 &#x1f31f;效果 &#x1f31f;实现思路 要实现自动滚动&#xff0c;无非就…

[转载]田雪松硬笔行书临文征明《滕王阁序》_拔剑-浆糊的传说_新浪博客

原文地址&#xff1a;田雪松硬笔行书临文征明《滕王阁序》 作者&#xff1a;游目骋怀

【Acwing285】没有上司的舞会(树形dp)题目笔记

题目描述 题目分析 首先来看状态表示&#xff1a; f[u][1]&#xff1a;所有从以u为根的子树中选择&#xff0c;并且不选u这个点的情况之下的最大指数 f[u][0]&#xff1a;所有从以u为根的子树中选择&#xff0c;并且选择u这个点的情况之下的最大指数 然后看状态计算&#x…

leetcode 516. 最长回文子序列

2023.8.27 本题依旧使用dp算法做&#xff0c;可以参考 回文子串 这道题。dp[i][j]定义为&#xff1a;子串s[i,j] 的最长回文子串。 直接看代码: class Solution { public:int longestPalindromeSubseq(string s) {vector<vector<int>> dp(s.size(),vector<int&…

pandas由入门到精通-描述性统计量

pandas基础介绍-命令模版 描述性统计量pandas 统计函数相关与协方差唯一值&#xff0c;频次统计,成员关系1. Series.unique()2. Series/DataFrame/array.value_counts()3. Series.isin()4. get_indexer() 索引对应转换 本文介绍pandas中一些常用的描述性统计量相关知识&#xf…

网易 腾讯 新浪手机新闻客户端横向对比评测

这段时间关于iPhone新闻客户端的事件获得不少关注&#xff0c;一张截图对比在微博上四处转发&#xff0c;不过只有一个界面对比也说明不了问题吧&#xff0c;想知道这些新闻客户端是不是如此相似&#xff0c;还是要认真对比瞧瞧。 参赛选手&#xff1a;网易新闻/腾讯新闻/掌中…

乔布斯女儿嘲讽iPhone 14没新意;高德打车AR实景找车功能上线;Go语言报告:错误处理仍然是个挑战|极客头条

「极客头条」—— 技术人员的新闻圈&#xff01; CSDN 的读者朋友们早上好哇&#xff0c;「极客头条」来啦&#xff0c;快来看今天都有哪些值得我们技术人关注的重要新闻吧。 整理 | 梦依丹 出品 | CSDN&#xff08;ID&#xff1a;CSDNnews&#xff09; 一分钟速览新闻点&…

极客日报:iPhone卫星功能仅用于紧急通信;韩国通过立法禁止苹果、谷歌垄断支付系统;Linux 5.14 版本发布

一分钟速览新闻点&#xff01; 小米集团加入开源专利社区 OIN饿了么&#xff1a;延长扬州会员一个月的权益阿里云教育推出钉钉课后服务系统华为 P50 Pro 推送鸿蒙更新淘宝更换新的 Slogan 为“淘宝太好逛了吧”鸿蒙 OS 2 升级用户破 7000 万&#xff01;近 100 款机型可升级网…

jQuery Mobile开发的新闻阅读器,适应iphone和android手机

程序员都很赖&#xff0c;你懂的&#xff01; 我们经常上新浪&#xff0c;腾讯&#xff0c;雅虎等各大网站上面看新闻&#xff0c;他们也都各自推出了自家的手机新闻阅读器。今天我自己使用jQuery Mobile 来实现这一功能。图片大小上传限制了大小250*400先看看iphone上的效果&a…

递归算法学习——全排列

目录 ​编辑 一&#xff0c;问题描述 1.例子&#xff1a; 题目接口&#xff1a; 二&#xff0c;问题分析和解决 1.问题分析 2.解题代码 一&#xff0c;问题描述 首先我们得来先看看全排列的问题描述。全排列问题的问题描述如下&#xff1a; 给定一个不含重复数字的数组 n…

2023年流行编曲软件哪个好用?flstudio有免费的吗 flstudio免费插件都有哪些

2023年流行的主流宿主编曲软件哪个好用&#xff0c;现在几款流行的主流宿主编曲软件包括FL Studio、Cubase、Pro Tools、Sonar、Logic Pro、Studio One等等。 对于新手学习来说我个人更推荐FL Studio 21&#xff0c;为什么说FL Studio 21 适合新手呢&#xff1f;自然是有道理的…

免费音频转换器,畅享音乐无边界。这些软件助你一键转换

嘿&#xff01;你是否有过这样的经历&#xff0c;当你想在特定设备上播放自己珍藏的音频时&#xff0c;却发现文件格式不兼容而无法播放&#xff1f;别灰心&#xff0c;我有个小秘诀要告诉你——音频格式转换&#xff01;通过将音频文件转换为适当的格式&#xff0c;你可以轻松…