springBoot --- JavaMailSender发送电子邮件

JavaMailSender

1、添加依赖

1
2
3
<dependency>				
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、配置文件

1
spring.mail.host=smtp.qq.com spring.mail.username=⽤户名 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

3、使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class ApplicationTests	{

@Autowired
private JavaMailSender mailSender;

@Test
public void sendSimpleMail() throws Exception {
//1、简单格式
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("dyc87112@qq.com");
message.setTo("dyc87112@qq.com");
message.setSubject("主题:简单邮件");
message.setText("测试邮件内容");
mailSender.send(message);

//2、复杂
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setFrom("dyc87112@qq.com");
helper.setTo("dyc87112@qq.com");
helper.setSubject("主题:有附件");
helper.setText("有附件的邮件");
//helper.setText("<html><body><img src=\"cid:weixin\" ></body></html>", true) ;
FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
//helper.addInline("weixin",file);
helper.addAttachment("附件-1.jpg",file);
helper.addAttachment("附件-2.jpg",file);
mailSender.send(mimeMessage);
}
}

4、发送模板邮件:

1
2
3
4
<dependency>				
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
</dependency>

在 resources/templates/ 下,创建⼀个模板⻚⾯ template.vm :

1
2
3
4
5
<html>
<body>
<h3>你好, ${username}, 这是⼀封模板邮件!</h3>
</body>
</html>

然后:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void sendTemplateMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("dyc87112@qq.com");
helper.setTo("dyc87112@qq.com");
helper.setSubject("主题:模板邮件");
Map<String, Object> model = new HashedMap();
model.put("username", "didi");
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,"template.vm", "UTF-8",model);
helper.setText(text, true);
mailSender.send(mimeMessage);}

文章作者: gqsu
文章链接: http://www.ipdax.com/0201/06/01/springBoot-Javamail发送邮件/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 技术笔记分享
支付宝打赏
微信打赏