SpringBoot配置邮件发送
发表于更新于
字数总计:550阅读时长:2分钟阅读量: 成都
获取QQ邮箱授权码
进入到QQ邮箱官网,依次点击设置 -> 账号 -> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 -> 管理服务 -> 生成授权码
按照提示生成授权码,并复制好授权码
配置
Maven坐标
在pom.xml
的dependencies
标签下添加以下坐标:
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
|
配置文件
在配置文件application.yml
中添加如下配置:
1 2 3 4 5 6 7 8 9 10 11 12 13
| spring: mail: host: smtp.qq.com port: 465 username: xxxxxxxxxqq.com password: xxxxxxxxxxxxx properties: mail.smtp.auth: true mail.smtp.starttls.enable: true mail.smtp.socketFactory.port: 465 mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory default-encoding: UTF-8
|
服务类
服务接口
1 2 3 4 5 6 7 8 9 10 11 12
| import org.springframework.stereotype.Service;
@Service public interface EmailService {
void sendMail(String to, String subject, String body); }
|
接口实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| 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.Service;
@Service public class EmailServiceImpl implements EmailService { @Value("${spring.mail.username}") private String username;
@Autowired private JavaMailSender javaMailSender;
public void sendMail(String to, String subject, String body) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(username); message.setTo(to); message.setSubject(subject); message.setText(body);
javaMailSender.send(message); } }
|
测试
编写以下测试代码并运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest class EmailServiceImplTest { @Autowired private EmailService emailService;
@Test void sendMail() { emailService.sendMail("收件人邮箱@example.com", "测试邮件", "你好啊,这是一封测试邮件"); } }
|
参考文章
Java实现邮件发送 超详细!!!(以QQ邮箱个人版和企业版为例)