springboot实现发送邮件开箱即用
- 环境
- 依赖包
- yml配置
- Service层
- Controller层
- 测试
环境
jdk17
springboot版本3.2.1
依赖包
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId><version>3.1.4</version>
</dependency>
yml配置
我用的是qq邮箱,port是465
如果用的是其他的邮箱,自己修改这个端口,可能是25
ssl:true这个必须配置,不加会报错
不要复制,自己输,复制格式会出错
邮箱就自己的邮箱
秘密要开启stmp的时候系统给那个,不是自己设置的qq邮箱秘密
spring:mail:host: smtp.qq.comport: 465username: xxxx@qq.compassword: xxxxdefault-encoding: UTF-8properties:mail:smtp:auth: truessl:enable: true
Service层
把setFrom里的邮箱换成自己的,就yml中配置那个
package com.example.demo;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;@Service
public class EmailService {@Autowiredprivate JavaMailSender javaMailSender;public void sendSimpleEmail(String to, String subject, String text) {SimpleMailMessage message = new SimpleMailMessage();message.setFrom("xxx@qq.com");message.setTo(to);message.setSubject(subject);message.setText(text);javaMailSender.send(message);}
}
Controller层
to后面的是收件人地址
package com.example.demo;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/email")
public class EmailController {@Autowiredprivate EmailService emailService;@GetMapping("/send")public String sendEmail() {String to = "xxx@qq.com";String subject = "邮件提醒";String text = "这是一条测试邮件";emailService.sendSimpleEmail(to, subject, text);return "邮件发送成功";}
}
测试
用postman直接请求对应的接口地址
不需要任何参数
测试结果如下