Appearance
SpringBoot邮件发送
1. 开启POP3/SMTP/IMAP服务

2. maven依赖
xml
<!-- Springboot 版本 2.1.10.RELEASE -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>3. 配置文件
#邮箱服务
spring.mail.host=smtp.163.com
spring.mail.username=xx@163.com
spring.mail.password=邮箱授权码4. 测试
java
/**
* @author zhanglei
*/
@Component
public class MailService {
@Value("${spring.mail.username}")
private String username;
@Resource
private MailSender mailSender;
/**
* 使用MailSender发送简单邮件
*
* @param to 对方邮件地址
* @param subject 主题
* @param text 内容
*/
public void sendSimpleMail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(username);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
message.setCc(username);
try {
mailSender.send(message);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}java
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringbootEmailApplicationTests {
@Resource
private MailService mailService;
@Test
public void contextLoads() {
mailService.sendSimpleMail("xx@qq.com","测试邮件","这是一封测试邮件!!!");
}
}