Demo下载地址
https://github.com/HelloSummer5/SendEmailDemo
说明
- spring提供了非常好用的
JavaMailSender
接口实现了邮件的发送,其中Spring Boot的Starter也为此提供了自动化配置 - QQ邮箱需要发送方开启smtp和获取授权码,开启方法:http://service.mail.qq.com/cgi-bin/help?subtype=1&&no=1001256&&id=28
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
application.properties配置
# 发送方电子邮箱服务器,如果是163就是stmp.163.com
spring.mail.host=smtp.qq.com
# 发送方邮箱
spring.mail.username=发送方邮箱
# 如果是QQ邮箱,就是发送方授权码
spring.mail.password=发送方授权码
# 通过验证
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
测试
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.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
import javax.mail.internet.MimeMessage;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SendemailApplicationTests {
@Autowired
private JavaMailSender javaMailSender;
@Test
public void contextLoads() throws Exception{
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
// 发送方邮箱
helper.setFrom("sender@qq.com");
// 接收方邮箱
helper.setTo("receiver@qq.com");
// 主题
helper.setSubject("主题:测试邮件");
// 内容
helper.setText("邮箱测试Test");
javaMailSender.send(mimeMessage);
}
}
最后PO个效果图,QAQ请忽略我多年前青涩的非主流昵称。