这篇文章主要介绍“springboot发送邮件功能怎么实现”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“springboot发送邮件功能怎么实现”文章能帮助大家解决问题。
发邮件是一个很常见的功能,在java中实现需要依靠JavaMailSender这个接口。在springboot项目中需要引入名为 spring-boot-starter-mail 的依赖,如果对邮件的格式有要求的话可以引入可以操作html文件的 spring-boot-starter-thymeleaf 依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
和其他自动化配置模块一样,在完成了依赖引入之后,还需要在application.properties
中配置相应的属性值,否则运行方法会一直报空指针。
1、打开idea,点击左上角工具栏file按钮 ,新建一个boot项目
2.点击next ,选择默认的依赖,常见的有数据库连接,web等
3、点击finsh,等待boot项目目录等生成。此时的目录是不全的需要自己新加java以及resources文件夹。右键项目选择
进行增加操作。
4、然后打开pom文件,引入依赖。
5、打开配置文件,写上对应的参数,
到此项目建成,开始写测试类。
1、建一个util类,写一个实现发送逻辑的业务类,没什么要写工具类,因为我想发送邮件的时候可以实现种格式,带附件带html样式以及可以异步操作的邮件,尤其异步大家都知道发邮件是很耗时的。
2、补一个异步调用的写法:
*需要异步的方法加@Async
*需要在启动类上加开启异步的方法,@EnableAsync
*注意可能应该是因为aop代理的缘故,被调用方法 和 调用处的代码都处在同一个类的话,只是相当于本类调用,并没有使用代理类 从而@Async并没有产生效果,就是在一个工具类。
3、代码 :带有附件的邮件
@Test
public void sendAttachmentsMail() {
Context context = new Context();
context.setVariable("agencyName", "11");
context.setVariable("busTypeName", "22");
context.setVariable("busAllowance", 33);
String emailContent = templateEngine.process("emailTeplate", context);
try {
emailService.sendAttachmentsMail(new String[]{"xxx.com"}, "测试提示", emailContent);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("send mail success!,please wait a few mintens");
}
/**
* fujian
* @throws Exception
*/
@Async
public void sendAttachmentsMail(String[] to, String subject, String contnet) throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("xxx.com");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(contnet,true);
Path picturePath = Paths.get("E:WorkFiles estBill", "test.png");
byte[] bytes = Files.readAllBytes(picturePath);
helper.addAttachment("附件-1.jpg", picturePath.toFile());
mailSender.send(mimeMessage);
}
邮件发送成功
关于“springboot发送邮件功能怎么实现”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4579551/blog/4351426