设置邮箱
这里以QQ邮箱为例,进入设置-帐户:
开始POP3/SMTP服务(这一步会得到一个密码,下面会用到):
编写代码
增加依赖pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
创建配置文件application.yml:
spring:
mail:
# qq邮箱用这个
host: smtp.qq.com
port: 587
# 邮箱号
username: xxxx@qq.com
# 开启POP3/SMTP时得到的密码
password: xxxxxx
default-encoding: utf-8
properties:
mail:
debug: true
创建控制器TestController.java:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private JavaMailSender mailSender;
@GetMapping("sendMail")
public String sendMail() {
// 创建简单邮件消息
SimpleMailMessage message = new SimpleMailMessage();
// 谁发的
message.setFrom("xxx@qq.com");
// 谁要接收
message.setTo("xxx@qq.com");
// 邮件标题
message.setSubject("subject");
// 邮件内容
message.setText("content");
try {
mailSender.send(message);
return "发送普通邮件成功";
} catch (MailException e) {
e.printStackTrace();
return "普通邮件方失败";
}
}
}
访问sendMail控制器,发送成功: