SpringBoot整合mail进行发送邮箱

Spring Boot整合邮箱进行发送

1. 添加依赖

在pom.xml文件中添加spring-boot-starter-mail依赖,如下所示:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. 配置邮件发送参数

在application.properties或application.yml文件中配置邮件发送参数,如下所示:

# 邮件服务器地址和端口号
spring.mail.host=smtp.qq.com
spring.mail.port=587
# 发件人邮箱账号和密码
spring.mail.username=your_email@qq.com
spring.mail.password=your_email_password
# 收件人邮箱账号(可以同时设置多个)
spring.mail.receivers=receiver1@example.com,receiver2@example.com
# 邮件编码格式
spring.mail.properties.mail.default-encoding=UTF-8

3.编写邮件发送服务类

创建一个邮件发送服务类,使用JavaMailSender接口实现邮件发送功能,如下所示:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;
    
    public void sendEmail(String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();  // 实例化邮件对象
        message.setFrom("[email protected]");  // 发件人邮箱账号
        message.setTo("[email protected],[email protected]");  // 收件人邮箱账号,多个账号用逗号分隔
        message.setSubject(subject);  // 邮件主题
        message.setText(text);  // 邮件内容
        javaMailSender.send(message);  // 发送邮件
    }
}

4. 调用邮件发送服务类的方法发送邮件

@Autowired
private EmailService emailService;
...
emailService.sendEmail("Hello World", "This is a test email sent by Spring Boot!");

你可能感兴趣的:(java服务端,spring,boot,后端,java,网易邮箱大师)