javaMail直接发送附件,无须生成临时文件
Posted 馥钰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaMail直接发送附件,无须生成临时文件相关的知识,希望对你有一定的参考价值。
以excel附件为例:
先引入依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
邮件发送服务:
@Service
public class MailService
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final JavaMailSender sender;
@Value("$spring.mail.username")
private String from;
public MailService(JavaMailSender sender)
this.sender = sender;
/**
* 利用helper设置各种邮件发送相关的信息
*/
private MimeMessageHelper setInfoByHelper(String to, String subject, String content, MimeMessage message)
throws MessagingException
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
return helper;
/**
* 发送带附件的邮件
* @param to 收件人列表
* @param subject 邮件标题
* @param content 邮件内容
* @param inputStreamSource 附件streamSource,可以这样获得:new ByteArrayResource(ByteArrayOutputStream.toByteArray());
* @param fileName 附件的文件名
*/
public void sendAttachmentsMail(String to, String subject, String content, InputStreamSource inputStreamSource, String fileName)
MimeMessage message = sender.createMimeMessage();
try
MimeMessageHelper helper = setInfoByHelper(to, subject, content, message);
helper.addAttachment(fileName, inputStreamSource);
sender.send(message);
logger.debug("带附件的邮件已经发送。");
catch (MessagingException e)
logger.error("发送带附件的邮件时发生异常!", e);
方法调用(测试用例):
利用ByteArrayOutputStream把excel文件输出到bytes[]中,然后由ByteArrayResource包装起来传递给邮件服务。
@Test
public void sendMailWithExcel() throws IOException
String[] headers = "col1","col2","col3";
// 声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++)
HSSFCell cell = row.createCell(i);
cell.setCellValue(headers[i]);
int rowIndex = 1;
for(int j=0; j<3; j++)
row = sheet.createRow(rowIndex);
rowIndex++;
HSSFCell cell1 = row.createCell(0);
cell1.setCellValue(j);
cell1 = row.createCell(1);
cell1.setCellValue(j+1);
cell1 = row.createCell(2);
cell1.setCellValue(j+2);
for (int i = 0; i < headers.length; i++)
sheet.autoSizeColumn(i);
ByteArrayOutputStream os = new ByteArrayOutputStream(1000);
wb.write(os);
wb.close();
InputStreamSource iss = new ByteArrayResource(os.toByteArray());
os.close();
mailService.sendAttachmentsMail("xjj@qq.com",
"attachmentMail subject",
"I have an attachment",
iss, "abc1.xlsx");
————————————————
版权声明:本文为CSDN博主「Clement-Xu」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ClementAD/article/details/78743663
以上是关于javaMail直接发送附件,无须生成临时文件的主要内容,如果未能解决你的问题,请参考以下文章
JavaMail 从字符串发送邮件附件 - 编码 UTF-8