本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程《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("[email protected]", "hello", "你好", "file");
return "success";
}
執行結果: