springboot发送email邮件
1.依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
2.配置
## QQ邮箱配置
spring:
mail:
host: smtp.qq.com #发送邮件服务器
username: 767632fafa267@qq.com #发送邮件的邮箱地址
password: aacckrutvbhwscibfae #客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
properties.mail.smtp.port: 465 #端口号465或587
#from: 1016767658@qq.com # 发送邮件的地址,和上面username一致
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
3.service接口
package com.xiya.service;
/**
* @author Administrator
*/
public interface EmailService {
/**
* 发送文本邮件
* @param to 收件人
* @param subject 主题
* @param content 内容
*/
void sendSimpleMail(String to, String subject, String content);
}
4.serviceImpl
package com.xiya.service;
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;
/**
* @author Administrator
*/
@Service
public class EmailServiceImpl implements EmailService {
/**
* Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
*/
@Autowired
private JavaMailSender mailSender;
/**
* 配置文件中我的qq邮箱
*/
@Value("${spring.mail.username}")
private String from;
/**
* 发送文本邮件
*
* @param to 收件人
* @param subject 主题
* @param content 内容
*/
@Override
public void sendSimpleMail(String to, String subject, String content) {
//创建SimpleMailMessage对象
SimpleMailMessage message = new SimpleMailMessage();
//邮件发送人
message.setFrom(from);
//邮件接收人
message.setTo(to);
//邮件主题
message.setSubject(subject);
//邮件内容
message.setText(content);
//发送邮件
mailSender.send(message);
}
}
5.测试代码
package com.xiya.test;
import com.xiya.service.EmailService;
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.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class EmailTest {
@Autowired
private EmailService emailService;
@Test
public void test1() {
emailService.sendSimpleMail("517787552@qq.com", "找回密码", "您的验证码为");
}
}