spring boot发送邮件

ops/2024/10/10 15:21:57/

文章目录

  • 项目目录结构
  • 添加maven依赖
  • application.yml配置发信人信息
  • 编码测试
    • 创建 Email 工具类 `EmailUtil`
    • 测试发送邮件

项目目录结构

在这里插入图片描述

添加maven依赖

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

application.yml配置发信人信息

我这里已qq邮箱为例,如果是其它邮箱也一样,需要修改 host

password 是授权码,不是登录密码
邮箱设置开启服务,生成授权码
在这里插入图片描述
在这里插入图片描述

spring:mail:host: smtp.qq.comusername: [发送邮箱账号]password: [邮箱授权码]default-encoding: UTF-8protocol: smtpport: 587properties:mail:stmp:ssl:enable: true

编码测试

创建 Email 工具类 EmailUtil

java">package com.example.demoboot.utils;import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;import java.io.File;
import java.io.IOException;
import java.util.Map;@Component
public class EmailUtil {@Value("${spring.mail.username}")private String from; // 发件人private MailSender mailSender;private JavaMailSender javaMailSender;  // JavaMailSender 继承了 MailSender ,可以发送更复杂的邮件,可以携带附件。private TemplateEngine templateEngine;@Autowiredpublic EmailUtil(MailSender mailSender, JavaMailSender javaMailSender, TemplateEngine templateEngine) {this.mailSender = mailSender;this.javaMailSender = javaMailSender;this.templateEngine = templateEngine;}/*** 发送一般邮件 -- 无附件* @param to      收件人* @param subject 主题* @param content 内容* @return 是否成功*/public boolean sendGeneralEmail(String subject, String content, String[] to) {// 创建邮件消息SimpleMailMessage message = new SimpleMailMessage();message.setFrom(from);// 设置收件人message.setTo(to);// 设置邮件主题message.setSubject(subject);// 设置邮件内容message.setText(content);// 发送邮件mailSender.send(message);return true;}/*** 发送带附件的邮件* @param to        收件人* @param subject   主题* @param content   内容* @param filePaths 附件路径* @return 是否成功*/public boolean sendAttachmentsEmail(String subject, String content, String[] to, String[] filePaths) throws MessagingException, IOException {// 创建邮件消息MimeMessage mimeMessage = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);helper.setFrom(from);// 设置收件人helper.setTo(to);// 设置邮件主题helper.setSubject(subject);// 设置邮件内容helper.setText(content);// 添加附件if (filePaths != null) {for (String filePath : filePaths) {ClassPathResource resource = new ClassPathResource(filePath);String filename = resource.getFilename();File file = resource.getFile();assert filename != null;helper.addAttachment(filename, file);}}// 发送邮件javaMailSender.send(mimeMessage);return true;}/*** 发送带静态图片资源的邮件,图片资源内嵌在消息主题中* @param to         收件人* @param subject    主题* @param content    内容* @param picPathMap 静态资源路径* @return 是否成功*/public boolean sendInlinePictureEmail(String subject, String content, String[] to, Map<String, String> picPathMap) throws MessagingException {// 创建邮件消息MimeMessage mimeMessage = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);// 设置发件人helper.setFrom(from);// 设置收件人helper.setTo(to);// 设置邮件主题helper.setSubject(subject);// html内容图片StringBuffer buffer = new StringBuffer();buffer.append("<html><body><div>");buffer.append(content);buffer.append("</div>包含以下图片:</br>");picPathMap.forEach((k, v) -> buffer.append("<img src=\'cid:").append(k).append("\'></br>"));buffer.append("</body></html>");helper.setText(buffer.toString(), true);// 指定讲资源地址picPathMap.forEach((k, v) -> {// FileSystemResource res = new FileSystemResource(new File(v));ClassPathResource res = new ClassPathResource(v);try {helper.addInline(k, res);} catch (MessagingException e) {e.printStackTrace();}});javaMailSender.send(mimeMessage);return true;}/*** 发送模板邮件* @param subject 主题* @param templateName  模板名称* @param templateData  模板参数* @param to    收件人* @return* @throws MessagingException*/public boolean sendTemplateEmail(String subject, String templateName, Map<String, Object> templateData, String[] to) throws MessagingException {Context context = new Context();context.setVariables(templateData);String content = templateEngine.process(templateName, context);// 创建邮件消息MimeMessage mimeMessage = javaMailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);helper.setFrom(from);// 设置收件人helper.setTo(to);// 设置邮件主题helper.setSubject(subject);// 设置邮件内容helper.setText(content, true);// 发送邮件javaMailSender.send(mimeMessage);return true;}
}

测试发送邮件

java">package com.example.demoboot.controller;import com.example.demoboot.utils.EmailUtil;
import jakarta.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;import java.io.IOException;
import java.util.HashMap;@Controller
@RequestMapping("/mail")
public class MailController {private EmailUtil emailUtil;@Autowiredpublic MailController(EmailUtil emailUtil) {this.emailUtil = emailUtil;}@ResponseBody@RequestMapping("/send/1")public String send() {emailUtil.sendGeneralEmail("测试邮件", "测试邮件内容", new String[]{"xxxxx@qq.com"});return "success";}@ResponseBody@RequestMapping("/send/2")public String send2() {HashMap<String, String> map = new HashMap<>();map.put("1", "static/1.jpg");map.put("2", "static/2.jpg");try {emailUtil.sendInlinePictureEmail("测试邮件", "测试邮件内容", new String[]{"xxxxx@qq.com"}, map);} catch (MessagingException e) {throw new RuntimeException(e);}return "success";}@ResponseBody@RequestMapping("/send/3")public String send3() {try {emailUtil.sendAttachmentsEmail("测试邮件", "测试邮件内容", new String[]{"xxxxx@qq.com"}, new String[]{"static/1.jpg", "static/2.jpg"});} catch (MessagingException | IOException e) {throw new RuntimeException(e);}return "success";}@ResponseBody@RequestMapping("/send/4")public String send4() throws MessagingException {HashMap<String, Object> map = new HashMap<>();map.put("info", "测试邮件");map.put("say", "你好!!!!!!!!");emailUtil.sendTemplateEmail("测试邮件", "mailTemplate", map, new String[]{"762741385@qq.com"});return "mailTemplate";}
}

http://www.ppmy.cn/ops/123556.html

相关文章

从0开始linux(12)——命令行参数与环境变量

欢迎来到博主的专栏&#xff1a;从0开始linux 博主ID&#xff1a;代码小豪 文章目录 命令行参数环境变量 我们先打断一下关于进程的话题&#xff0c;博主先来介绍两个东西&#xff0c;分别是命令行参数与环境变量。那么有人看到这就会问了&#xff0c;难道说命令行参数和环境变…

使用Materialize制作unity的贴图,Materialize的简单教程,Materialize学习日志

Materialize 官网下载地址&#xff1a;http://boundingboxsoftware.com/materialize/ github源码地址&#xff1a;https://github.com/BoundingBoxSoftware/Materialize 下载地址&#xff1a;http://boundingboxsoftware.com/materialize/getkey.php 下载后解压运行exe即可 …

萤火php端: 查询数据的时候报错: “message“: “Undefined index: pay_status“,

代码&#xff1a;getGoodsFromHistory <?php // ---------------------------------------------------------------------- // | 萤火商城系统 [ 致力于通过产品和服务&#xff0c;帮助商家高效化开拓市场 ] // -----------------------------------------------------…

【QT Quick】C++交互:调用QML函数

在本节中&#xff0c;我们将深入探讨如何在C中调用QML函数。这项功能非常常用&#xff0c;尤其是在需要将C逻辑与QML界面进行交互时。我们将重点关注invokeMethod函数&#xff0c;它支持多种参数形式&#xff0c;并允许我们灵活地处理不同的调用场景。 invokeMethod概述 invo…

TypeScript 中枚举类型的理解?应用场景有哪些

文章目录 一、是什么二、使用数字枚举字符串枚举异构枚举本质 三、应用场景 一、是什么 枚举是一个被命名的整型常数的集合&#xff0c;用于声明一组命名的常数,当一个变量有几种可能的取值时,可以将它定义为枚举类型 通俗来说&#xff0c;枚举就是一个对象的所有可能取值的集…

微信小程序15天

UniApp(Vue3组合式API)和微信小程序15天学习计划 第1天&#xff1a;开发环境配置和基础知识 UniApp和微信小程序概述及对比安装并配置HBuilderX(UniApp)和微信开发者工具创建第一个UniApp Vue3项目和微信小程序项目了解两个平台的项目结构差异配置外部浏览器和各种小程序模拟…

影视cms泛目录用什么程序?苹果cms二次开发泛目录插件

影视CMS泛目录一般使用的程序有很多种&#xff0c;&#xff08;maccmscn&#xff09;以下是其中几种常见的程序&#xff1a; WordPress&#xff1a;WordPress是一个非常流行的开源内容管理系统&#xff0c;可以通过安装一些插件来实现影视CMS泛目录功能。其中&#xff0c;一款常…

JDBC介绍

JDBC&#xff1a; ( Java DataBase Connectivity )&#xff0c;就是使用Java语言操作关系型数据库的一套API。 本质&#xff1a; Sun公司官方定义的一套操作所有关系型数据库的规范&#xff0c;即接口。 各个数据库厂商去实现这套接口&#xff0c;提供数据库驱动jar包。 我们…