1.首先开启自己邮箱客户端的功能,开启之后会给你一个密码
- 导入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
-
配置文件
spring.mail.username=你的邮箱 spring.mail.password=第一步配置会有一段密文 spring.mail.host=smtp.qq.com #开启加密验证 spring.mail.properties.mail.stml.ssl.enable=true
4.测试邮箱发送,我这边把方法直接给直接提取出来了
@SpringBootTest
class SpringbootQuerzApplicationTests {
@Autowired
private JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
HashMap<String, String> map = new HashMap<>();
map.put("1.jpg","D:\\桌面和图片\\4k壁纸\\长发少女黑色吊带裙 好看的4k动漫美女壁纸3840x2160_彼岸图网.jpg");
map.put("2.jpg","D:\\桌面和图片\\4k壁纸\\带眼镜的女生 面部 好看的人物插画绘画4k高清动漫壁纸_彼岸图网.jpg");
try {
sendMail("你好1","<div style='color=red'>你好</div>",true,map,"1625397016@qq.com","1625397016@qq.com");
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
*
* @param Title 邮箱的标题
* @param text 邮箱的内容
* @param htmlflag 是否开启邮箱内容的html格式
* @param Attachment 附件
* @param to 发送给谁
* @param from 你自己配置的
* @throws MessagingException
*/
private void sendMail(String Title, String text, Boolean htmlflag, Map<String,String>Attachment,String to,String from) throws MessagingException {
//邮件消息
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装,增加更过功能
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
//正文
//标题
messageHelper.setSubject(Title);
//内容
messageHelper.setText(text,htmlflag);
//附件
if(!Attachment.isEmpty()){
List<String> keylist =new ArrayList<>(Attachment.keySet());
for (int i = 0; i < keylist.size(); i++) {
messageHelper.addAttachment(keylist.get(i),new File(Attachment.get(keylist.get(i))));
}
}
//用户
messageHelper.setTo(to);
//发送给谁
messageHelper.setFrom(from);
mailSender.send(mimeMessage);
}
}