1.添加依赖
在pom.xml中添加下面的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、添加邮件配置参数
(1)yml配置,(注意:mail中host的配置前缀需要是smtp),邮件可以是QQ,163,126等
spring:
# 外置jdbc和log配置文件
profiles:
# 外置jdbc和log配置文件
active: jdbc,log,redis
# 缓存配置
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
# thymeleaf配置
thymeleaf:
prefix: classpath:/templates/
check-template-location: true
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5
cache: false
# main配置
mail:
host: smtp.228.com.cn
username: xxxxxxxx@228.com.cn
password: xxxxxx
protocol: smtp
port: 25
(2)properties配置
spring.mail.default-encoding=utf-8
spring.mail.host=smtp.228.com.cn
spring.mail.username=xxx@228.com.cn
spring.mail.password=xxxx
spring.mail.protocol=smtp
spring.mail.port=25
3、测试demo
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MailController {
@Autowired
JavaMailSender javaMailSender;
@RequestMapping("/sendMail")
public String sendMain(){
//建立邮件消息
SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
//消息发送者
simpleMailMessage.setFrom("xxxxxxx@228.com.cn");
//接受者
simpleMailMessage.setTo("xxxxxxx@qq.com");
//消息标题
simpleMailMessage.setSubject("测试啊");
//内容
simpleMailMessage.setText("哈喽啊");
try {
javaMailSender.send(simpleMailMessage);
} catch (MailException ex) {
System.err.println(ex.getMessage());
return "fail";
}
return "success";
}
}
4、测试
运行项目后打开 http://127.0.0.1:port/sendMail
测试结果: