介绍
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
添加配置
- 使用的是163邮箱,请先登陆163邮箱,设置开启smtp,获取授权码
spring.mail.host=smtp.163.com
spring.mail.username=xxxxxx@163.com
#注意,此处不是登陆密码,而是开启smtp获取的授权码
spring.mail.password=xxxxxx
# 启动ssl
spring.mail.properties.mail.smtp.ssl.enable=true
# 启动tls
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
编写代码
@RestController
@Slf4j
public class DemoController {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String fromUser;
@GetMapping(value = "/send")
public Response send() {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(fromUser);
helper.setTo("xxxxxx@qq.com");
helper.setSubject("Hello");
helper.setText("你好!");
javaMailSender.send(mimeMessage);
} catch (Exception e) {
log.error("", e);
}
return Response.success();
}
}