天天看點

如何實作發送帶附件的郵件? | 帶你讀《SpringBoot實戰教程》之二十六

上一篇:如何在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中:

如何實作發送帶附件的郵件? | 帶你讀《SpringBoot實戰教程》之二十六

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";          
    }           

執行結果:

如何實作發送帶附件的郵件? | 帶你讀《SpringBoot實戰教程》之二十六
如何實作發送帶附件的郵件? | 帶你讀《SpringBoot實戰教程》之二十六

配套視訊