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);
相关推荐
Knight_AL20 分钟前
Spring Boot 实现 DOCX 转 PDF(基于 docx4j 的轻量级开源方案)
spring boot·pdf·开源
兜兜风d'24 分钟前
基于 Spring Boot + RabbitMQ 实现应用通信
spring boot·rabbitmq·java-rabbitmq·1024程序员节
小范同学_24 分钟前
Spring集成WebSocket
java·spring boot·websocket·spring·1024程序员节
不爱编程的小九九8 小时前
小九源码-springboot088-宾馆客房管理系统
java·开发语言·spring boot
抹香鲸之海9 小时前
Prometheus+Grafana实现Springboot服务监控
spring boot·grafana·prometheus
摇滚侠10 小时前
Spring Boot 3零基础教程,WEB 开发 内嵌服务器底层源码分析 笔记48
spring boot·笔记
萌新小码农‍11 小时前
SpringBoot+alibaba的easyexcel实现前端使用excel表格批量插入
前端·spring boot·excel
韩立学长11 小时前
【开题答辩实录分享】以《租房小程序的设计和实现》为例进行答辩实录分享
java·spring boot·小程序
zl97989911 小时前
SpringBoot-数据访问之MyBatis与Redis
java·spring boot·spring
重生之我是Java开发战士12 小时前
【Java EE】快速上手Spring Boot
java·spring boot·java-ee