上一篇:如何在SpringBoot中实现邮件的发送? | 带你读《SpringBoot实战教程》之二十五
下一篇:如何发送基于模板的邮件? | 带你读《SpringBoot实战教程》之二十七
本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,点击查看视频内容。
实现发送带附件的邮件
在上一节的案例中添加代码:
EmailService:
//发送带附件的邮件
void sendAttachmentMail(String sendTo, String title, String content, File file);
EmailServiceImpl:
//发送带附件的邮件
@Override
public void sendAttachmentMail(String sendTo, String title, String content, File file) {
MimeMessage msg = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(msg, true);
helper.setFrom(emailConfig.getEmailFrom());
helper.setTo(sendTo);
helper.setSubject(title);
helper.setText(content);
FileSystemResource r = new FileSystemResource(file);
helper.addAttachment("附件", r);
} catch (Exception e) {
e.printStackTrace();
}
mailSender.send(msg);
}
将文件放在resources下的static中:
EmailController:
@RequestMapping("/attach")
@ResponseBody
public String sendAttachmentEmail() {
File file = new File("src/main/resources/static/66.txt");
emailService.sendAttachmentMail("465008297@qq.com", "hello", "你好", "file");
return "success";
}
执行结果: