jdk17
springboot版本3.2.1
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>3.1.4</version>
</dependency>
我用的是qq邮箱,port是465
如果用的是其他的邮箱,自己修改这个端口,可能是25
ssl:true这个必须配置,不加会报错
不要复制,自己输,复制格式会出错
邮箱就自己的邮箱
秘密要开启stmp的时候系统给那个,不是自己设置的qq邮箱秘密
spring:
mail:
host: smtp.qq.com
port: 465
username: xxxx@qq.com
password: xxxx
default-encoding: UTF-8
properties:
mail:
smtp:
auth: true
ssl:
enable: true
把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 {
@Autowired
private 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);
}
}
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 {
@Autowired
private EmailService emailService;
@GetMapping("/send")
public String sendEmail() {
String to = "xxx@qq.com";
String subject = "邮件提醒";
String text = "这是一条测试邮件";
emailService.sendSimpleEmail(to, subject, text);
return "邮件发送成功";
}
}
用postman直接请求对应的接口地址
不需要任何参数
测试结果如下