spring-boot 使用 spring-boot-starter-mail 发送邮件

参考文档 https://docs.spring.io/spring-framework/docs/5.3.10/reference/html/integration.html#mail-usage-simple

在pom.xml文件中引入mail启动器

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

修改application.properties文件

spring.mail.host=smtp.163.com # 发送邮件的服务地址
spring.mail.username= # 发送邮件的用户名
spring.mail.password= # 发送邮件的密码

发送邮件测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SendMail {
    @Autowired
    private JavaMailSender javaMailSender;

    @Test
    public void sendMessage() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo("收件人邮箱地址");
        simpleMailMessage.setSubject("主题");
        simpleMailMessage.setText("正文");
        simpleMailMessage.setFrom("发件人邮箱地址");
        javaMailSender.send(simpleMailMessage);
    }
}
posted @ 2021-12-28 18:35  GetcharZp  阅读(400)  评论(0编辑  收藏  举报