其他分享
首页 > 其他分享> > 记录一次简单的springboot发送邮件功能

记录一次简单的springboot发送邮件功能

作者:互联网

场景:经常在我们系统中有通过邮件功能找回密码,或者发送生日祝福等功能,今天记录下springboot发送邮件的简单功能

  1.引入maven

<!--        邮件开发-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2.以qq邮箱为例,开启pop3/smtp,并记住授权码

 


 

 

 

 3.在配置文件中配置相关信息(密码为刚刚开启的授权码,不是你邮箱登录密码)

 

 

 4.创建发送邮箱类

package com.chen.dockerdemo.maildemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
* @author chenxiaokang
* @date 2020/1/14 16:14
*/
@Component
public class EmailService {
@Autowired
private JavaMailSender mailSender;

/**
* 简单的邮件发送测试
*/
public void sendMsg(){
SimpleMailMessage mailMessage = new SimpleMailMessage();
// 邮件发送者
mailMessage.setFrom("729***064@qq.com");
// 邮件接收者
mailMessage.setTo("cxk***787***39@163.com");
// 邮件主题
mailMessage.setSubject("java 测试邮箱发送");
// 邮件内容
mailMessage.setText("你已成功收到我发的消息");
mailSender.send(mailMessage);
}
}

5.编写测试类


package com.chen.dockerdemo.controller;

import com.chen.dockerdemo.config.MyPro;
import com.chen.dockerdemo.maildemo.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
* @author chenxiaokang
* @date 2020/1/14 13:54
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
class HelloWordControllerTest {

@Autowired
EmailService emailService;
@Test
void maiLSend(){
emailService.sendMsg();
}
}
6.邮件发送成功

 


 这里只是简单的记录下了发送邮件最基本的配置,更多业务要求慢慢探索!

 
 
 
 
 
 

标签:springboot,mailMessage,springframework,发送,org,import,com,邮件
来源: https://www.cnblogs.com/xiaokangk/p/12192819.html