今天分享一篇 java 发送 QQ 邮件的功能
环境:
jdk 1.8 + springboot 2.6.3 + maven 3.9.6
邮件功能依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置:
spring.mail.protocol=smtp
spring.mail.port=587
# qq邮箱
spring.mail.host=smtp.qq.com
# 发件人邮箱
[email protected]
# 这里替换为自己的发件人邮箱的授权码
spring.mail.password=xxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
获取授权码:
登录 QQ 邮箱网页版 -> 设置 -> 账号
往下翻:找到下面这一块区域,如果没有开启服务的,直接开启服务即可 然后点击管理服务
然后点击生成授权码
注意:生成后需要记住,授权码只展示这一次,如果忘了,可以生成多个
发送简单邮件
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 Test1Controller {
@Autowired
private JavaMailSender mailSe