当前位置:   article > 正文

【JAVA】将文件添加为附件并发送邮件_java发送邮件excel附件

java发送邮件excel附件

要将 Excel 文件添加为邮件附件并发送,使用 JavaMail API 和 Apache POI 库来实现。代码片段如下,演示如何将 Excel 文件添加为附件并发送邮件:

  1. package com.jeeplus.sbptapi.upload.task;
  2. import cn.hutool.extra.spring.SpringUtil;
  3. import com.jeeplus.quartz.domain.ScheduleJob;
  4. import com.jeeplus.quartz.domain.Task;
  5. import com.jeeplus.sbptapi.jkapi.service.SbptDataUploadApiService;
  6. import com.jeeplus.sbptapi.upload.service.dto.UploadResultsDTO;
  7. import com.jeeplus.sys.domain.SysConfig;
  8. import com.jeeplus.sys.service.SysConfigService;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.apache.poi.ss.usermodel.Row;
  11. import org.apache.poi.ss.usermodel.Sheet;
  12. import org.apache.poi.ss.usermodel.Workbook;
  13. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  14. import org.quartz.DisallowConcurrentExecution;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import javax.mail.*;
  17. import javax.mail.internet.InternetAddress;
  18. import javax.mail.internet.MimeBodyPart;
  19. import javax.mail.internet.MimeMessage;
  20. import javax.mail.internet.MimeMultipart;
  21. import java.io.File;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.text.SimpleDateFormat;
  25. import java.util.List;
  26. import java.util.Properties;
  27. /**
  28. * 定时通过邮箱反馈上传结果
  29. */
  30. @Slf4j
  31. @DisallowConcurrentExecution
  32. public class DataUploadResultsTask extends Task {
  33. @Autowired
  34. private SbptDataUploadApiService sbptDataUploadApiService;
  35. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
  36. /**
  37. * 30分钟执行一次
  38. * 定时执行上传接口
  39. */
  40. // @Scheduled(cron="0 1 * * * ?")
  41. @Override
  42. public void run(ScheduleJob scheduleJob) {
  43. try {
  44. List<UploadResultsDTO> uploadResults = sbptDataUploadApiService.getUploadResults();
  45. // 创建Excel文件
  46. String filePath = "上报结果报告.xlsx";
  47. createExcel(uploadResults, filePath);
  48. // 发送邮件
  49. String toEmail = scheduleJob.getRemarks(); // 收件人
  50. String subject = "上报结果报告"; // 邮件标题
  51. sendEmailWithAttachment(toEmail, subject, filePath);
  52. } catch (Exception e) {
  53. e.getMessage();
  54. }
  55. }
  56. /**
  57. * 获取结果数据
  58. * @param dataList 结果数据
  59. * @param filePath 文件信息
  60. * @throws IOException
  61. */
  62. public static void createExcel(List<UploadResultsDTO> dataList, String filePath) throws IOException {
  63. Workbook workbook = new XSSFWorkbook();
  64. Sheet sheet = workbook.createSheet("Data");
  65. // 创建表头
  66. Row headerRow = sheet.createRow(0);
  67. headerRow.createCell(0).setCellValue("GS");
  68. headerRow.createCell(1).setCellValue("RQ");
  69. headerRow.createCell(2).setCellValue("FWZT");
  70. // ...
  71. // 写入数据
  72. int rowNum = 1;
  73. for (UploadResultsDTO data : dataList) {
  74. Row row = sheet.createRow(rowNum++);
  75. row.createCell(0).setCellValue(data.getGs());
  76. row.createCell(1).setCellValue(data.getRq());
  77. row.createCell(2).setCellValue(data.getFwzt());
  78. }
  79. // 保存Excel文件
  80. try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
  81. workbook.write(outputStream);
  82. }
  83. }
  84. /**
  85. * 发送邮件
  86. * @param toEmail 收件人
  87. * @param subject 邮件标题
  88. * @param attachmentPath 附件
  89. */
  90. public static void sendEmailWithAttachment(String toEmail, String subject, String attachmentPath) {
  91. SysConfig config = SpringUtil.getBean(SysConfigService.class).getById("1");
  92. String from = config.getMailName(); // 发件人
  93. String host = config.getSmtp(); // 邮箱服务器地址
  94. Properties properties = System.getProperties();
  95. properties.setProperty("mail.smtp.host", host);
  96. properties.put("mail.smtp.auth", "true");
  97. Session session = Session.getDefaultInstance(properties, new Authenticator() {
  98. @Override
  99. public PasswordAuthentication getPasswordAuthentication() {
  100. return new PasswordAuthentication(from, config.getMailPassword());
  101. }
  102. });
  103. File attachment = new File(attachmentPath);
  104. try {
  105. MimeMessage mimeMessage = new MimeMessage(session);
  106. mimeMessage.setFrom(new InternetAddress(from));
  107. mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
  108. mimeMessage.setSubject(subject);
  109. // 创建邮件附件
  110. MimeBodyPart attachmentPart = new MimeBodyPart();
  111. attachmentPart.attachFile(attachment);
  112. // 创建多部分消息
  113. Multipart multipart = new MimeMultipart();
  114. multipart.addBodyPart(attachmentPart);
  115. // 设置邮件内容
  116. mimeMessage.setContent(multipart);
  117. Transport.send(mimeMessage);
  118. System.out.println("发送邮件成功");
  119. } catch (MessagingException e) {
  120. e.printStackTrace();
  121. } catch (IOException e) {
  122. e.printStackTrace();
  123. } finally {
  124. // 删除临时文件
  125. attachment.delete();
  126. }
  127. }
  128. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/591808
推荐阅读
相关标签
  

闽ICP备14008679号