<!--对邮件的支持jar-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
spring:
mail:
host: smtp.qq.com # 设置邮箱主机(服务商),这里使用QQ邮件服务器
username: 1134135987@qq.com # 设置用户名
password: xxxxxxx # 设置密码,该处的密码是QQ邮箱开启SMTP的授权码而非QQ密码
properties:
mail:
smtp:
auth: true # 必须进行授权认证,它的目的就是阻止他人任意乱发邮件
starttls: #SMTP加密方式:连接到一个TLS保护连接
enable: true
required: true
package cn.itsource;
import cn.itsource.pethome.MainApp;
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.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest(classes = MainApp.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class EmailTest {
@Autowired
private JavaMailSender javaMailSender;
@Test
public void send(){
SimpleMailMessage mailMessage = new SimpleMailMessage();
//设置发送人
mailMessage.setFrom("1134135987@qq.com");
//邮件主题
mailMessage.setSubject("新型冠状病毒防护指南");
//邮件内容
mailMessage.setText("好好在家待着.....");
//收件人
mailMessage.setTo("wujiangbo2018@163.com");
javaMailSender.send(mailMessage);
}
}
运行成功之后,收件箱中确实收到了:
@Test
public void send2() throws Exception{
//创建复杂邮件对象
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//发送复杂邮件的工具类
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
helper.setFrom("1134135987@qq.com");
helper.setSubject("新型冠状病毒防护指南");
//第二个参数 true 代表是否是一个html内容
helper.setText("<h1>好好在家待着敲代码</h1>",true);
//添加附件
helper.addAttachment("文件名.jpg", new File("D:\\ITSource\\test\\test.png"));
helper.addAttachment("压缩文件", new File("D:\\ITSource\\test\\test.zip"));
//收件人
helper.setTo("wujiangbo2018@163.com");
//发送邮件
javaMailSender.send(mimeMessage);
}
测试成功: