配置
打开https://mail.qq.com/ 登录你自己的qq账号
选择账户
点击开启 STMP服务拿到授权码:
pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.yml配置
spring:
mail:
# 配置 SMTP 服务器地址
host: smtp.qq.com
# 发送者邮箱
username: 957354171@qq.com
# 配置密码,注意不是真正的密码,而是刚刚申请到的授权码
password:
# 端口号465或587
port: 587
# 默认的邮件编码为UTF-8
default-encoding: UTF-8
Java集成EmailService
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
@Component
@Slf4j
public class EmailUtils {
@Autowired
JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
String username;
public void sendHtml(String title, String html, String to) {
MimeMessage mailMessage = javaMailSender.createMimeMessage();
//需要借助Helper类
MimeMessageHelper helper = new MimeMessageHelper(mailMessage);
try {
helper.setFrom(username); // 必填
helper.setTo(to); // 必填
// helper.setBcc("密送人"); // 选填
helper.setSubject(title); // 必填
helper.setSentDate(new Date());//发送时间
helper.setText(html, true); // 必填 第一个参数要发送的内容,第二个参数是不是Html格式。
javaMailSender.send(mailMessage);
} catch (MessagingException e) {
log.error("发送邮件失败", e);
}
}
}