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

场景

项目搭建专栏:

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

实现最简单的带标题以及文本内容的邮件发送:

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

实现

在上面成功实现发送简单邮件的基础上

发送附件就是添加一个文件

这里在static下添加一个文件

SpringBoot中整合Mail实现发送带附件的邮件_第1张图片

在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

SpringBoot中整合Mail实现发送带附件的邮件_第2张图片

SpringBoot中整合Mail实现发送带附件的邮件_第3张图片

SpringBoot中整合Mail实现发送带附件的邮件_第4张图片

 

SpringBoot中整合Mail实现发送带附件的邮件_第5张图片

 

源码下载

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

你可能感兴趣的:(SpringBoot,SpringBoot实战项目)