Spring Boot 发送邮件

Spring Boot 发送邮件

准备工作

引入依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

邮箱开启SMTP三方登录授权

常用邮箱有开启SMTP授权引导;QQ邮箱

配置邮件服务器

yaml 复制代码
spring:
  mail:
    host: smtp.qq.com
    # 未开启ssl 使用 25,开启ssl 使用 465 或 587
    port: 465
    username: xxx
    password: xxx
    properties:
      mail.smtp.auth: true
      # 开启ssl 上面 port 使用 465 或 587;不开启使用 25
      mail.smtp.ssl.enable: true
#      mail.smtp.ssl.trust: ${spring.mail.host}
#      mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
#      mail.smtp.socketFactory.port: 465
#      mail.smtp.starttls.enable: true
#      mail.smtp.starttls.required: true
#      mail.debug: true

发送邮件

普通文本邮件

java 复制代码
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo("收件人");
    message.setFrom("发件人");
    message.setSubject("测试邮件");
    message.setText("Java 给你发的测试邮件");
    mailSender.send(message);

复杂邮件

html邮件

含附件的邮件

java 复制代码
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setTo("收件人");
helper.setFrom("发件人");
helper.setSubject("主题");
// html
helper.setText("内容", true);
Path xxxx = Path.of("xxxx");
PathResource file = new PathResource(xxxx);
// 附件
helper.addAttachment(file.getFilename(), file);
相关推荐
unique_perfect8 小时前
vue2与springboot实现deepseek打印机聊天
spring boot·websocket·ai·vue2·deepseek
哈哈老师啊9 小时前
Springboot学生综合测评系统hxtne(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring boot
气π11 小时前
【JavaWeb】——(若依 + AI)-基础学习笔记
java·spring boot·笔记·学习·java-ee·mybatis·ruoyi
老华带你飞12 小时前
列车售票|基于springboot 列车售票系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·spring
汝生淮南吾在北12 小时前
SpringBoot+Vue在线考试系统
vue.js·spring boot·后端·毕业设计·毕设
script.boy12 小时前
基于spring boot校园二手交易平台的设计与实现
java·spring boot·后端
猿与禅13 小时前
Spring Boot 4.0 完整核心特性及实践指南
java·spring boot·后端·spring·重大升级·springboot4.0
曲莫终14 小时前
SpringBoot使用AutoConfiguration自动配置Bean
spring boot
E***U94515 小时前
从新手到入门:如何判断自己是否真的学会了 Spring Boot
数据库·spring boot·后端
invicinble15 小时前
javase-异常体系
开发语言·spring boot