springboot发送邮件功能怎么实现
发邮件是一个很常见的功能,在java中实现需要依靠JavaMailSender这个接口。在springboot项目中需要引入名为spring-boot-starter-mail的依赖,如果对邮件的格式有要求的话可以引入可以操作html文件的spring-boot-starter-thymeleaf依赖。org.springframework.bootspring-boot-starter-mailorg.springframework.bootspring-boot-starter-thymeleaf和其
发邮件是一个很常见的功能,在java中实现需要依靠JavaMailSender这个接口。在springboot项目中需要引入名为 spring-boot-starter-mail 的依赖,如果对邮件的格式有要求的话可以引入可以操作html文件的 spring-boot-starter-thymeleaf 依赖。
org.springframework.boot spring-boot-starter-mail org.springframework.boot spring-boot-starter-thymeleaf
和其他自动化配置模块一样,在完成了依赖引入之后,还需要在application.properties中配置相应的属性值,否则运行方法会一直报空指针。
一、新建一个springboot项目。
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);
}邮件发送成功

Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















