日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

SpringBoot中整合Mail实现发送带附件的邮件

發布時間:2025/3/19 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot中整合Mail实现发送带附件的邮件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

場景

項目搭建專欄:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/column/info/35688

實現最簡單的帶標題以及文本內容的郵件發送:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/89320985

實現

在上面成功實現發送簡單郵件的基礎上

發送附件就是添加一個文件

這里在static下添加一個文件

在Controller中新增方法

@RequestMapping("sendAttachmentEmail")@ResponseBodypublic String sendAttachmentEmail() {File file = new File("src/main/resources/static/badao.gif");emailService.sendAttachmentMail("****@qq.com", "測試附件發送", "霸道流氓氣質", file);return "success";}

在service中添加方法

package com.example.demo.email;import java.io.File;import org.springframework.stereotype.Service;@Service public interface EmailService {//發送簡單郵件void sendSimpleMail(String sendTo,String title,String content);//發送帶附件的郵件void sendAttachmentMail(String sendTo,String title,String content,File file); }

在實現類中添加方法

package com.example.demo.email;import java.io.File;import javax.mail.internet.MimeMessage;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; @Service public class EmailServiceImpl implements EmailService {@Autowiredprivate EmailConfig emailConfig;@Autowiredprivate JavaMailSender mailSender;@Overridepublic void sendSimpleMail(String sendTo, String title, String content) {//簡單郵件的發送SimpleMailMessage message = new SimpleMailMessage();message.setFrom(emailConfig.getEmailFrom());message.setTo(sendTo);message.setSubject(title);message.setText(content);mailSender.send(message);}//發送帶附件的郵件@Overridepublic void sendAttachmentMail(String sendTo, String title, String content, File file) {MimeMessage message =mailSender.createMimeMessage();try {MimeMessageHelper helper =new MimeMessageHelper(message,true);helper.setFrom(emailConfig.getEmailFrom());helper.setTo(sendTo);helper.setText(content);FileSystemResource resource = new FileSystemResource(file);helper.addAttachment("附件", resource);} catch (Exception e) {e.printStackTrace();}mailSender.send(message);}}

效果

啟動項目,訪問

http://localhost:8080/sendAttachmentEmail

?

?

源碼下載

https://download.csdn.net/download/badao_liumang_qizhi/11114809

總結

以上是生活随笔為你收集整理的SpringBoot中整合Mail实现发送带附件的邮件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。