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);
相关推荐
ZhengEnCi13 小时前
S02-SpringBoot实体类新增字段对已有数据的影响及自动DDL同步机制详解
数据库·spring boot
程序员张313 小时前
SpringBoot集成BCrypt密码加密库
java·spring boot·后端
9523614 小时前
RabbitMQ-基础操作
java·spring boot·分布式·后端·spring·rabbitmq
卓怡学长14 小时前
w266基于spring boot + vue 圣地延安美食乐享系统
java·数据库·vue.js·spring boot·spring·intellij-idea
Listen·Rain16 小时前
Springboot整合Ollama实现调用本地多模型
java·spring boot·后端
宠友信息17 小时前
多端即时通讯源码技术实践,Redis路由、MySQL持久化与Socket接入
spring boot·websocket·mysql·uni-app
Tom·Ge17 小时前
【Spring Boot 4】Spring Boot 4.0 AI Agent实战:Skills Agent + MCP协议集成
人工智能·spring boot·microsoft
Devin~Y17 小时前
电商场景下的Java面试实战:从Spring Boot微服务到Kafka、Redis与AI RAG
java·spring boot·redis·elasticsearch·spring cloud·微服务·kafka
白露与泡影18 小时前
用 Spring Boot + Vue + Fuzio 构建现代 Java 桌面应用
java·vue.js·spring boot
宠友信息19 小时前
Spring Boot与异步审核构建仿小红书源码内容发布全流程
java·数据库·spring boot·redis·mysql·oracle·uni-app