欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot发送电子邮件(附源码)

程序员文章站 2024-03-24 08:24:34
...

Demo下载地址

https://github.com/HelloSummer5/SendEmailDemo

说明

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

application.properties配置

# 发送方电子邮箱服务器,如果是163就是stmp.163.com
spring.mail.host=smtp.qq.com
# 发送方邮箱
spring.mail.username=发送方邮箱
# 如果是QQ邮箱,就是发送方授权码
spring.mail.password=发送方授权码
# 通过验证
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

测试

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.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.internet.MimeMessage;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SendemailApplicationTests {

    @Autowired
    private JavaMailSender javaMailSender;

    @Test
    public void contextLoads() throws Exception{
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        // 发送方邮箱
        helper.setFrom("aaa@qq.com");
        // 接收方邮箱
        helper.setTo("aaa@qq.com");
        // 主题
        helper.setSubject("主题:测试邮件");
        // 内容
        helper.setText("邮箱测试Test");
        javaMailSender.send(mimeMessage);

    }

}

最后PO个效果图,QAQ请忽略我多年前青涩的非主流昵称。
SpringBoot发送电子邮件(附源码)

参考文章:https://www.jianshu.com/p/295c57a20382