SpringBoot整合邮件功能(带附件)

news/2024/9/28 23:15:50/

前言

这篇文章只是记录一下在开发中使用邮箱功能

本人在项目中需要使用邮箱发送带附件的邮件,我们的附件可能是在线的阿里云OSS,也可能是系统生成的Excel,写了一个工具类,方便使用。

整合流程

QQ邮箱作为案例
1、添加依赖

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

2、添加配置

java">spring:mail:username: ************@qq.comdefault-encoding: utf-8host: smtp.qq.comport: 465 #端口号465587password: **************#客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的properties:mail:smtp:auth: truesocketFactory:class: javax.net.ssl.SSLSocketFactoryfallback: falsessl:enable: truetrust: smtp.qq.com

3、工具类

java">import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;/*** 邮箱工具*/
@Slf4j
@Component
public class MailUtils {@Autowiredprivate JavaMailSender mailSender;/*** 配置文件中我的qq邮箱*/@Value("${spring.mail.username}")private String username;/*** 发送邮件-不包含附件** @param fromAliasName 别名* @param toMail        发送目标邮箱* @param subject       主题* @param content       内容*/public void sendMail(String fromAliasName, String toMail, String subject, String content) {sendMailOssFile(fromAliasName, toMail, subject, content, null);}/*** 发送邮件工具-OSS在线文件** @param fromAliasName 别名* @param toMail        发送目标邮箱* @param subject       主题* @param content       内容* @param fileList      附件OSS地址*/public void sendMailOssFile(String fromAliasName, String toMail, String subject, String content, List<String> fileList) {try {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);// 设置发件人别名(如果未设置别名就默认为发件人邮箱)if (fromAliasName != null && !fromAliasName.trim().isEmpty()) {helper.setFrom(new InternetAddress(username, fromAliasName));} else {helper.setFrom(username);}helper.setTo(toMail);helper.setSubject(subject);helper.setText(content, true);if (fileList != null && !fileList.isEmpty()) {for (String filePath : fileList) {String[] split = filePath.split("/");// 将输入流转换为ResourceURL url = new URL(filePath);DataSource dataSource = new URLDataSource(url);helper.addAttachment(split[split.length - 1], dataSource);}}//发送邮件mailSender.send(message);log.info("邮件已经发送。");} catch (MalformedURLException e) {log.error("URL 格式错误: {}", e.getMessage(), e);} catch (MessagingException | UnsupportedEncodingException e) {log.error("发送邮件时发生异常: {}", e.getMessage(), e);}}/*** 发送邮件工具-普通文件** @param fromAliasName 别名* @param toMail        发送目标邮箱* @param subject       主题* @param content       内容* @param fileList      附件*/public void sendMailFile(String fromAliasName, String toMail, String subject, String content, List<File> fileList) {try {MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);// 设置发件人别名(如果未设置别名就默认为发件人邮箱)if (fromAliasName != null && !fromAliasName.trim().isEmpty()) {helper.setFrom(new InternetAddress(username, fromAliasName));} else {helper.setFrom(username);}helper.setTo(toMail);helper.setSubject(subject);helper.setText(content, true);if (fileList != null && !fileList.isEmpty()) {for (File file : fileList) {helper.addAttachment(file.getName(), new FileSystemResource(file));}}//发送邮件mailSender.send(message);log.info("邮件已经发送。");} catch (MessagingException | UnsupportedEncodingException e) {log.error("发送邮件时发生异常!", e);}}}

http://www.ppmy.cn/news/1530873.html

相关文章

服务器配置虚拟环境及离线安装python

本篇文章基于已经装好conda环境进行哈&#xff0c;不会安装conda可参考服务器离线安装anaconda-CSDN博客 1.打印现有虚拟环境列表 conda env list&#xff0c;可以看见我现在有base、ai、py38三个环境 2.删除指定虚拟环境 conda remove -n py38 --all&#xff0c;回车后输入ye…

Qwen2-VL论文阅读笔记

第1章介绍 论文亮点&#xff1a; 1、 the Naive Dynamic Resolution mechanism 2、Multimodal Rotary Position Embedding (M-RoPE) 2D Rotary Position Embedding 3、统一图片和视频的处理范式、增i强视觉感知能力 4、LVLMs的scaling laws&#xff1a;2B、8B、72B 5、 dynamic…

SpringBoot之登录校验关于JWT、Filter、interceptor、异常处理的使用

什么是登录校验&#xff1f; 所谓登录校验&#xff0c;指的是我们在服务器端接收到浏览器发送过来的请求之后&#xff0c;首先我们要对请求进行校验。先要校验一下用户登录了没有&#xff0c;如果用户已经登录了&#xff0c;就直接执行对应的业务操作就可以了&#xff1b;如果用…

甘蔗茎节检测系统源码分享

甘蔗茎节检测检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Vis…

List几种遍历方法速度

准备数据 ArrayList<Integer> list new ArrayList<Integer>();for (int i 0; i < 100000000; i) {list.add(i); }1.for循环 for (int i 0; i < list.size(); i) {Integer str list.get(i); }2.for-each循环 for (Integer vo:list) {}3.Lambda list.forEa…

为人机交互保持预见性丨基于G32A1445的T-BOX应用方案

T-BOX是一种集成了通信、计算和控制功能的车载信息处理终端&#xff0c;通过车辆与云端、移动网络等进行数据交互&#xff0c;用于车、人、外部环境的互联互通&#xff0c;支持车辆定位、车载通信、远程控制、故障诊断、数据传输、紧急呼叫等功能&#xff0c;帮助车辆实现更加智…

机器学习之非监督学习(二)异常检测(基于高斯概率密度)

机器学习之非监督学习&#xff08;二&#xff09;异常检测&#xff08;基于高斯概率密度&#xff09; 0. 文章传送1.案例引入2.高斯正态分布3.异常检测算法4.异常检测 vs 监督学习5.算法优化6.代码实现 0. 文章传送 机器学习之监督学习&#xff08;一&#xff09;线性回归、多…

Vue.js与Flask/Django后端配合:构建高效Web应用

在当今的Web开发领域&#xff0c;前后端分离已成为一种主流的开发模式。Vue.js 作为前端框架的佼佼者&#xff0c;以其轻量级、响应式数据绑定和组件化的特点&#xff0c;受到了广大开发者的喜爱。而后端方面&#xff0c;Flask 和 Django 则是 Python 社区中非常流行的两个Web框…