springboot发送邮件

很久之前就想写一个总结的,一直没写,今天刚好又碰见了发送邮箱验证码的需求,刚好记录一波

一.核心依赖如下:

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/> <!-- lookup parent from repository -->
</parent><!--spring boot web的依赖-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><!-- mail 依赖 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency><!--thymeleaf模版依赖-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency><!--freemarker模版依赖-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

二.获取QQ邮箱授权码(QQ邮箱-设置-账户-POP3/SMTP服务开启,发送短信即可获取,记得保存好)

三、配置application.yml文件

spring:mail:host: smtp.qq.comusername: 发件的邮箱password: 发件邮箱的授权码properties:mail:smtp:auth: trueport: 587      starttls:enable: truerequired: true

这里不指定properties.mail.smtp.port的话在windons下面可以直接发送,但是到我linux上面就没法了,我猜测不写的话可能就会默认到25号端口,但是我linux又没法连上25号端口,只能 连上587,因此我手动指定。

linux上面测试可以连通邮箱服务的命令:

1.sudo yum install telnet

2.telnet smtp.qq.com 25

像我这样25端口一直卡到超时,那肯定没办法连通了。

不过587就很顺畅得连上了。

大家可以自己测试一下,否则java是抓异常得一直等到超时才会抓到,很浪费时间!!

四、EmailService和EmailServiceImpl

public interface EmailService {/*** 发送模版邮件* @param receiverName* @param information 模版参数名(html页面)*/void sendTemplateEmail(String receiverName, String code,String information);
}
package com.exam.serviceimpl.common;import com.exam.conf.EmailConfig;
import com.exam.service.common.EmailService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.thymeleaf.TemplateEngine;import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;@Service
public class EmailServiceImpl implements EmailService {@Autowiredprivate EmailConfig emailConfig;@Autowiredprivate JavaMailSender mailSender;@Autowiredprivate TemplateEngine templateEngine;@Autowiredprivate FreeMarkerConfigurer markerConfigurer;//发送模版邮件@Overridepublic void sendTemplateEmail(String receiverName,String code, String information) {MimeMessage message = mailSender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(message,true);helper.setFrom(new InternetAddress(emailConfig.getEmailFrom(),"xxxxxxx","UTF-8"));helper.setTo(receiverName);helper.setSubject("Online Exam");//封装模版使用的数据Map<String,Object> map = new HashMap<>();map.put("code",code);//            1.FreeMarker
//            1-1 获取FreeMarker模版Template markertemplate = markerConfigurer.getConfiguration().getTemplate(information);
//            1-2 将模版内容转为字符串类型并将参数传入String markertTtml = FreeMarkerTemplateUtils.processTemplateIntoString(markertemplate, map);
//            1-3 将字符串作为邮件内容helper.setText(markertTtml,true);//            //2.Thymeleaf
//            //2-1 获取Thymeleaf模版
//            Context context = new Context();
//            context.setVariable("username","瑶");
//            //2-2 将模版内容转为字符串类型并将参数传入
//            String thymeleafHtml = templateEngine.process("thymeleafTemplate", context);
//            helper.setText(thymeleafHtml,true);}catch (Exception e){e.printStackTrace();}mailSender.send(message);}}
helper.setFrom(new InternetAddress(emailConfig.getEmailFrom(),"xxxxxx","UTF-8"));指定发件人得时候,可以给发件人改成自己想要的字符串,类似于,将xxx替换成自己想要的字符串

五.EmailConfig

package com.exam.conf;import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Data
@Component
public class EmailConfig {/*** 发件人*/@Value("${spring.mail.username}")private String emailFrom;
}

六、在resources/templates下新建freemarkerTemplate.htmlthymeleafTemplate.html用来做文件模版。由于我使用的freemarkerTemplate,因此可能存在一定样式,大家可以自行修改。

当前freemarkerTemplate渲染出来得样式是这个样子

freemarkerTemplate.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>freemarkerTemplate</title><style>body {font-family: Arial, sans-serif;margin: 0;padding: 20px;line-height: 1.6;}.container {max-width: 600px;margin: 0 auto;background-color: #f9f9f9;padding: 20px;border-radius: 5px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);}.verification-code {display: block;font-size: 28px;font-weight: bold;color: #333;background-color: rgba(166, 165, 160, 0.2);padding: 8px 12px;border-radius: 5px;margin-bottom: 10px;}.thanks {font-size: 16px;color: #666;}</style>
</head>
<body>
<div class="container"><p>Verification Code:</p><p><span class="verification-code">${code}</span></p><p>Please use this code within <strong>10 minutes</strong>.</p><p class="thanks">Thank you for using our service.</p>
</div>
</body>
</html>
thymeleafTemplate.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head><meta charset="UTF-8"><title>thymeleafTemplate</title>
</head>
<body>
<span th:text="${username}"></span>,你好,感谢您的使用,这是你的激活邮件,请点击下面的链接进行激活。<br></body>
</html>

最后就是使用了,很简单

emailService.sendTemplateEmail(email, code, "freemarkerTemplate.html");

注意,"freemarkerTemplate.html"这个就是对应得resources/templates的模板名字

至此,就可以把邮件发送融合入自己需要用的地方了。

参考博客:使用Springboot发送邮件(QQ邮箱)整合笔记_springboot mail qq邮箱发送邮件-CSDN博客

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

docker部署opensearch —— 筑梦之路

OpenSearch 简介 •OpenSearch 是一款开源的分布式搜索引擎(从 ElasticSearch 特定版本分叉而来)&#xff0c;可以执行快速、可扩展的全文搜索、应用程序和基础设施监控、安全和事件信息管理、运营健康跟踪等用例。 •OpenSearch 具有多种功能和插件&#xff0c;可以帮助索引、…

谷歌推出适用于安卓设备的“Find My Device”网络,功能类似苹果Find My

谷歌今日推出了适用于安卓设备的“Find My Device”网络&#xff0c;其功能类似于苹果的“Find My”网络&#xff0c;旨在帮助用户定位丢失、被盗的安卓产品。 安卓的“Find My Device”网络可以利用数以亿计运行 Android 9 或更高版本的安卓设备&#xff0c;通过蓝牙信号追踪丢…

自动化运维(二十五)Ansible 实战过滤器插件和缓存插件

Ansible 支持多种类型的插件&#xff0c;这些插件可以帮助你扩展和定制 Ansible 的功能。每种插件类型都有其特定的用途和应用场景。今天我们一起学习 过滤器插件和缓存插件。 一、 过滤器插件&#xff08;Filter Plugins&#xff09; Ansible 过滤器插件&#xff08;Filter …

批量记录收支明细,高效记录当天的收支明细并查看每个支出占比,轻松掌握开销

在繁忙的现代生活中&#xff0c;我们时常因为琐碎的财务事务而分心。为了帮助您更好地管理财务&#xff0c;我们推出了这款智能财务助手&#xff0c;让您可以高效记录每天的收支明细&#xff0c;并轻松掌握每个支出的占比。从此告别混乱&#xff0c;让财务管理变得简单明了 第…

gym界面修改

资料&#xff1a;https://blog.csdn.net/weixin_46178278/article/details/135962782 在gym环境中使用mujoco的时候&#xff0c;有一个很难受的地方&#xff0c;界面上没有实时显示动作空间和状态空间状态的地方。 gym自己原始带的环境是用pygame画的图&#xff0c;所以在定义…

【前端】es-drager 图片同比缩放 缩放比 只修改宽 只修改高

【前端】es-drager 图片同比缩放 缩放比 ES Drager 拖拽组件 (vangleer.github.io) 核心代码 //初始宽 let width ref(108)//初始高 let height ref(72)//以下两个变量 用来区分是单独的修改宽 还是高 或者是同比 //缩放开始时的宽 let oldWidth 0 //缩放开始时的高 let o…

JWT重放漏洞如何攻防?你的系统安全吗?

大家好&#xff0c;我是石头~ 在数字化浪潮席卷全球的今天&#xff0c;JSON Web Token&#xff08;JWT&#xff09;作为身份验证的利器&#xff0c;已成为众多Web应用的首选方案。 然而&#xff0c;正如硬币有两面&#xff0c;JWT的强大功能背后也隐藏着潜在的安全风险&#xf…

2024mathorcup数学建模D题思路分析-量子计算在矿山设备配置及运营中的建模应用

# 1 赛题 D 题 量子计算在矿山设备配置及运营中的建模应用 随着智能技术的发展&#xff0c;智慧矿山的概念越来越受到重视。越来越多的 设备供应商正在向智慧矿山整体解决方案供应商转型&#xff0c;是否具备提供整体 解决方案的能力&#xff0c;也逐步成为众多矿山设备企业的核…

UVC摄像头在虚拟机Ubuntu16.04使用的正确姿势

前言&#xff1a;在Windows使用UVC摄像头是正常的&#xff0c;但在虚拟机Ubuntu中使用可以识别到&#xff0c; 但是一直没有数据出来&#xff0c;一度怀疑是摄像头不行&#xff0c;后来经过仔细研究&#xff0c;才发现是虚拟机usb设置有点问题。一、虚拟机USB设置USB 3.0,不然没…

【C++类和对象】上篇

&#x1f49e;&#x1f49e; 前言 hello hello~ &#xff0c;这里是大耳朵土土垚~&#x1f496;&#x1f496; &#xff0c;欢迎大家点赞&#x1f973;&#x1f973;关注&#x1f4a5;&#x1f4a5;收藏&#x1f339;&#x1f339;&#x1f339; &#x1f4a5;个人主页&#x…

数据仓库—ETL工具与技术:数据仓库的坚实基石

作为一名长期从事数据仓库领域的专业人士&#xff0c;我深知ETL&#xff08;Extract, Transform, Load&#xff09;工具和技术在构建和维护数据仓库中的核心作用。ETL不仅是数据流动的桥梁&#xff0c;更是确保数据质量和支持业务智能决策的关键环节。在这篇文章中&#xff0c;…

字节码文件的组成

字节码文件的组成 字节码文件的组成1 以正确的姿势打开文件2 字节码文件的组成2.1 基本信息2.2 常量池2.3 字段2.4 方法2.5 属性 3 字节码常用工具3.1 javap3.2 jclasslib插件3.3 Arthas 4 字节码常见指令 字节码文件的组成 1 以正确的姿势打开文件 字节码文件中保存了源代码…

Git 解决分支冲突

一、前言 一直习惯于 add commit push 的三步走&#xff0c;偶然间看到了一个评论说在 push 之前还有一个 pull&#xff0c;小小的疑问就埋在了我的心里。于是我就先了解了 pull 的工作原理&#xff0c;就是先拉取代码&#xff08;fetch&#xff09;再合并分支&#xff08;mer…

matlab使用教程(42)—常见的二维图像绘制方法

这个博客用于演示如何在 MATLAB 中创建曲线图、条形图、阶梯图、误差条形图、极坐标图、针状图、散点图。 1.曲线图 plot 函数用来创建 x 和 y 值的简单线图。 x 0:0.05:5; y sin(x.^2); figure plot(x,y) 运行结果&#xff1a; 线图可显示多组 x 和 y 数据。 x 0:0.05:…

git撤销提交

要在Git中撤销最近的一次提交&#xff0c;可以使用以下命令&#xff1a; git reset --soft HEAD^&#xff1a;这将撤销最后一次提交&#xff0c;但保留更改内容在暂存区。 git reset --mixed HEAD^&#xff1a;默认选项&#xff0c;撤销提交和暂存区的更改&#xff0c;不过不删…

旧版本jquery升级新版本后如何处理兼容性问题

前言 最近项目在漏洞扫描过程中发现现在的jquery版本受多个跨站点脚本漏洞影响&#xff0c;需要升级jquery版本。 1、首先下载高版本的jquery&#xff0c;我这里升级的是3.6.0 2、对应的bootstrap版本也要升级&#xff0c;这里升级的是3.3.7 本来以为替换完这两个文件后&#…

STM32H7定时器TIM1-TIM17中断、PWM实现

STM32H7定时器TIM1-TIM17中断、PWM实现 高级定时器硬件框图定时器模式时基输出PWM定时器输入捕获 TIM1-TIM17的中断配置TIM1-TIM17的PWM输出 STM32H7 支持的定时器有点多&#xff0c;要简单的区分下。STM32H7 支持 TIM1-TIM8&#xff0c;TIM12-TIM17 共14 个定时器&#xff0c;…

Traefik不同版本之间的差异?

Traefik 是一款流行的开源反向代理和负载均衡器&#x1f504;&#xff0c;它被广泛用于容器化&#x1f4e6;和微服务架构&#x1f310;中。从其首次发布以来&#xff0c;Traefik 经历了多个版本的更新&#xff0c;每个版本都带来了重要的新特性和改进&#x1f6e0;️。在本文中…

GitHub repository - Watch - Star - Fork - Follow

GitHub repository - Watch - Star - Fork - Follow References 眼睛图标旁边写着 Watch 字样。点击这个按钮就可以 Watch 该仓库&#xff0c;今后该仓库的更新信息会显示在用户的公开活动中。Star 旁边的数字表示给这个仓库添加 Star 的人数。这个数越高&#xff0c;代表该仓库…

【数据结构】习题之链表的回文结构和相交链表

&#x1f451;个人主页&#xff1a;啊Q闻 &#x1f387;收录专栏&#xff1a;《数据结构》 &#x1f389;前路漫漫亦灿灿 前言 今日的习题是关于链表的&#xff0c;分别是链表的回文结构和相交链表的判断。 链表的回文结构 题目为&#xff1a;链表的回文结…