当前位置:
首页 >
前端技术
> javascript
>内容正文
javascript
SpringBoot中整合Mail实现发送带附件的邮件
生活随笔
收集整理的这篇文章主要介绍了
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实现发送带附件的邮件的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: SpringBoot中整合Mail实现发
- 下一篇: SpringBoot中整合Mail实现发