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")
 @ResponseBody
 public 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 {


 @Autowired
 private EmailConfig emailConfig;
 
 @Autowired
 private JavaMailSender mailSender;
 
 @Override
 public 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);
 }


 //发送带附件的邮件
 @Override
 public 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值