1、添加依赖pom.xml
<!-- 邮箱服务 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、添加application.properties
# 发件人邮箱
spring.mail.username=**********@qq.com
# QQ邮箱授权码(不是登录密码!)
spring.mail.password=**************
# 服务器
spring.mail.host=smtp.qq.com
# 端口(SSL 专用 465)
spring.mail.port=465
# 编码
spring.mail.default-encoding=UTF-8
# 必须加的 SSL 安全配置(解决 530 错误)
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
3、包装接口(可有可无)
package com.cooker.lottery_system.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.stereotype.Component;
@Component
public class MailUtil {
private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);
@Value(value = "${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
/**
* 发邮件
*
* @param to: 目标邮箱地址
* @param subject: 标题
* @param context: 正文
* @return
*/
public Boolean sendSampleMail(String to, String subject, String context) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(context);
try {
mailSender.send(message);
} catch (Exception e) {
logger.error("向{}发送邮件失败!", to, e);
return false;
}
return true;
}
}
4、调用方法
import com.cooker.lottery_system.common.utils.MailUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class MailTest {
@Autowired
private MailUtil mailUtil;
@Test
void sendMail(){
mailUtil.sendSampleMail("*******@qq.com","标题","正文");
}
}