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);
相关推荐
码农小野17 分钟前
基于Vue.js和SpringBoot的地方美食分享网站系统设计与实现
vue.js·spring boot·美食
sealaugh3234 分钟前
spring boot(学习笔记第十二课)
spring boot·笔记·学习
FREE技术2 小时前
基于java+springboot+vue实现的畅销图书推荐系统(文末源码+lw+ppt)23-500
java·vue.js·spring boot
Jinyi5032 小时前
Spring Boot 高级配置:如何轻松定义和读取自定义配置
java·spring boot·后端·spring·java-ee·maven·intellij-idea
虫小宝2 小时前
Spring Boot中的API文档生成
java·spring boot·后端
虫小宝4 小时前
在Spring Boot中实现多线程任务调度
java·spring boot·spring
多多*13 小时前
每天一道面试题之浅浅讲一下java5中的自动装箱和自动拆箱
java·开发语言·spring boot·后端·spring
hummhumm14 小时前
数据结构第3节: 抽象数据类型
数据结构·spring boot·spring·spring cloud·java-ee·maven·intellij-idea
qxlxi15 小时前
【SpringBoot】SpringBoot内置Servlet容器源码分析-Tomcat
spring boot·servlet·tomcat
破晓的历程15 小时前
Spring Boot的无缝衔接:深入解析与实践
数据库·spring boot·后端