0
点赞
收藏
分享

微信扫一扫

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



实现

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

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

这里在static下添加一个文件

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

在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实现发送带附件的邮件_ide_02

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

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

 

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

 


举报

相关推荐

0 条评论