springboot 发送带excel附件的邮件

从程序中动态查询出数据,生成excel文件,再加入到附件中

  public String sendAttendedFileMail() throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // multipart模式
        String[] tos={"abc.cn","def.cn"}; //收件人
        String[] ccs={"z.cn","x.cn","v.cn","b.cn"}; //抄送人
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        mimeMessageHelper.setTo(tos); //收件人
        mimeMessageHelper.setCc(ccs); //抄送人
        mimeMessageHelper.setFrom("[email protected]");
        mimeMessageHelper.setSubject("[Hello迈迪]-分销统计-迈格森渠道");

        StringBuilder sb = new StringBuilder();
        sb.append("");
        sb.append("

各位老师好:

"); sb.append("

本邮件为系统自动发送,如有问题请联系Hello迈迪技术部。

"); sb.append("

祝好!

"); sb.append(""); // 启用html mimeMessageHelper.setText(sb.toString(), true); // 设置附件 XSSFWorkbook workbook = null; InputStream in = null; try { workbook = saleYzOrderService.exportOrder(0,3012); //parentId只取前四位 //临时缓冲区 ByteArrayOutputStream out = new ByteArrayOutputStream(); //创建临时文件 workbook.write(out); byte[] bookByteAry = out.toByteArray(); in = new ByteArrayInputStream(bookByteAry); } catch (Exception e) { // logger.error("export orderList error!", e); } mimeMessageHelper.addAttachment("分销订单详情表.xlsx", new ByteArrayResource(IOUtils.toByteArray(in)), "application/vnd.ms-excel;charset=UTF-8"); try { workbook = saleYzOrderService.exportCount(); //临时缓冲区 ByteArrayOutputStream out = new ByteArrayOutputStream(); //创建临时文件 workbook.write(out); byte[] bookByteAry = out.toByteArray(); in = new ByteArrayInputStream(bookByteAry); } catch (Exception e) { // logger.error("export orderList error!", e); } mimeMessageHelper.addAttachment("分销订单统计表.xlsx", new ByteArrayResource(IOUtils.toByteArray(in)), "application/vnd.ms-excel;charset=UTF-8"); // 发送邮件 mailSender.send(mimeMessage); return "邮件已发送"; }

 

 

参考:

https://blog.csdn.net/chinawszjr/article/details/53490633

https://blog.csdn.net/codes_life/article/details/79989166

https://www.jianshu.com/p/5eb000544dd7

你可能感兴趣的:(java)