今天尝试了一下使用Spring boot发送邮件,发现非常方便,这里做个记录
1.可以在https://start.spring.io/直接创建项目,下载下来导入到IDEA中。
2.在Spring Boot的工程中的pom.xml中引入spring-boot-starter-mail依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
maven项目会自动导入jar包,今天遇到了一次导入jar包报错的情况,去本地maven项目删除重新导入就可以了。
3.以QQ邮箱为例,在application.properties中加入如下配置(注意替换自己的用户名和密码):
spring.mail.host=smtp.qq.com
spring.mail.username=@qq.com
spring.mail.password=
spring.mail.default-encoding=utf-8
4.这里用最简单的邮件为例
package com.yh.mail.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;
@Service
public class mailService {
@Value("${spring.mail.username}")
private String from ;
@Autowired
private JavaMailSender mailSender;
public void sendSimpleMail(String to , String subject,String content){
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
message.setFrom(from);
mailSender.send(message);
}
}
package com.yh.mail.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class serviceTest {
@Resource
mailService mailservice;
@Test
public void sendMail(){
mailservice.sendSimpleMail("@qq.com","测试","测试");
}
}
直接运行测试类就可以了。