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);
相关推荐
小蒜学长40 分钟前
乡政府管理系统设计与实现(代码+数据库+LW)
数据库·spring boot·后端·学习·旅游
MiniFlyZt1 小时前
excel的导入和下载(poi)
spring boot·spring·excel
做想做的,1 小时前
el-table表格样式设置单元格样式方法 :cell-class-name
前端·javascript·vue.js·spring boot
程序媛学姐1 小时前
SpringBoot缓存抽象:@Cacheable与缓存管理器配置
java·spring boot·缓存
学长论文辅导2 小时前
基于SpringBoot的校园二手交易平台(计算机毕设-JAVA)
java·spring boot·毕业设计·论文·管理系统·校园二手交易平台
尚学教辅学习资料2 小时前
基于SpringBoot+Vue的校园跑腿原生小程序
vue.js·spring boot·小程序·校园跑腿
奋斗的小方2 小时前
Springboot基础篇(5):自定义 MyBatis Starter
spring boot·后端·mybatis
皮皮林5513 小时前
SpringBoot + ResponseBodyEmitter 实时异步流式推送,优雅!
spring boot
MacroZheng3 小时前
Spring 官宣接入 DeepSeek,太香了!
java·spring boot·后端
Biehmltym6 小时前
【架构差异】SpringとSpringBoot:Bean机制的深入剖析与自动配置原理
java·spring boot·spring