GitHub
src="//ghbtns.com/github-btn.html?user=je-ge&repo=spring-boot&type=watch&count=true" scrolling="0" width="110" height="20">需求产生
发送邮件的需求比较常见,如找回密码、事件通知等
添加Maven email依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
修改配置文件application.properties
#Spring集成邮件发送的相关配置
#使用163邮箱,修改自己的邮箱帐号和密码
#spring.mail.host=smtp.163.com
#spring.mail.username=username@163.com
#spring.mail.password=password
#如果使用qq邮箱,修改自己的邮箱帐号和授权码
spring.mail.host=smtp.qq.com
spring.mail.username=1272434821@qq.com
#授权码是QQ邮箱推出的,用于登录第三方客户端的专用密码。
spring.mail.password=axfbjuksoiovoooo
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
需要将username@163.com和password修改成自己的163的邮箱帐号和密码
或者使用qq邮箱,这个需要授权码
http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
发送简单邮件
package com.jege.spring.boot.email;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:邮件发送测试类
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SendMailTest {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String username;
@Test
public void testSendSimple() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(username);
message.setTo("1272434821@qq.com");
message.setSubject("标题");
message.setText("内容部份");
javaMailSender.send(message);
}
}
发送附件
发送模板邮件
其他关联项目
- Spring Boot 菜鸟教程 13 注解定时任务
http://blog.csdn.net/je_ge/article/details/53434227 - Spring Boot 菜鸟教程 7 EasyUI-datagrid
http://blog.csdn.net/je_ge/article/details/53365189
源码地址
https://github.com/je-ge/spring-boot
如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
您的支持将鼓励我继续创作!谢谢!