【Java】SpringBoot集成邮箱发送
✨
AI总结摘要
本文是一篇关于Spring Boot集成邮箱发送邮件的教程。主要介绍了使用Spring Boot发送邮件的步骤,包括开通邮箱POP3、导入maven依赖、配置application.yml、实现Service和测试发送等五个步骤。文章详细解释了每个步骤的具体操作和注意事项,如网易邮箱的POP3和IMAP开通方法、maven依赖的导入、application.yml的配置、IMailService接口的实现和邮件发送测试等。通过本文,读者可以了解如何在Spring Boot项目中集成邮箱发送邮件,实现用户创建账户发送验证码等功能。
AI Model: Baidu-ERNIE
Update At: 2024-10-23 20:24:37
【Java】SpringBoot集成邮箱发送
前言
使用SpringBoot邮箱继承,在用户创建账户发送验证码等情况时非常有效,主要分为下面几个步骤:
- 开通邮箱POP3
- 导入maven依赖
- 配置application.yml
- 实现Service
- 测试发送
1、开通邮箱POP3
非常的简单,我这里使用的是网易的yeah.net免费邮箱,开启POP3其实就可以了,我这里也开通了IMAP
学过计算机网络就知道这两个协议有啥区别了

注意看一下网易下面的提示

2、导入maven依赖
也是非常的简单,导入完同步更新一下
<!--spring mail 邮箱模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3、配置application.yml
spring:
mail:
host: smtp.yeah.net
username: [email protected]
password: 开启POP3协议后会给一个密码
default-encoding: UTF-8
注意这里的host使用邮箱提供的!
4、实现Service
先写一个IMailService接口
public interface IMailService {
void sendSimpleMailMessage(String to, String subject, String content);
}
实现这个接口
package top.woodwhale.blog.services.impl;
import lombok.extern.slf4j.Slf4j;
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;
import top.woodwhale.blog.services.IMailService;
@Slf4j
@Service
public class MailServiceImpl implements IMailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String sendFrom;
@Override
public void sendSimpleMailMessage(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sendFrom);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
log.info("简单邮件发送成功");
} catch (Exception e) {
log.error("发送简单邮件时发生异常", e);
}
}
}
5、测试发送
在工程的test文件夹中进行测试
注意使用@SpringBootTest
@SpringBootTest
public class TestMail {
@Autowired
private MailServiceImpl mailService;
public static String to = "[email protected]";
public static String subject = "test";
public static String content = "114514";
@Test
public void send() {
mailService.sendSimpleMailMessage(to,subject,content);
}
}
愉快的发送,愉快的接收

Thanks for reading :: Enf of this article :: Read other posts
Comment Below