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);
相关推荐
weixin_545019325 小时前
微信小程序智能商城系统(uniapp+Springboot后端+vue管理端)
spring boot·微信小程序·uni-app
一只码代码的章鱼7 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法
程序员小杰@8 小时前
【MCP教程系列】SpringBoot 搭建基于 Spring AI 的 SSE 模式 MCP 服务
人工智能·spring boot·spring
程序员buddha9 小时前
Spring & Spring Boot 常用注解整理
java·spring boot·spring
C_V_Better9 小时前
Java Spring Boot 控制器中处理用户数据详解
java·开发语言·spring boot·后端·spring
胡子洲9 小时前
Spring Boot 应用中实现基本的 SSE 功能
java·spring boot·后端
非著名架构师9 小时前
SpringBoot整合MQTT实战:基于EMQX构建高可靠物联网通信,从零到一实现设备云端双向对话
spring boot·mqtt·emqx
贰拾wan10 小时前
【Java-EE进阶】SpringBoot针对某个IP限流问题
java·spring boot·后端·idea
Paran-ia10 小时前
【2025版】Spring Boot面试题
java·spring boot·后端
雷袭月启10 小时前
Springboot实现重试机制
spring boot·重试机制