当前位置:   article > 正文

java 发邮件带excel附件,以流的形式发送附件,不生成excel文件_javamail发送附件不生成新的文件

javamail发送附件不生成新的文件

最近项目中是有个发送邮件的需求,但是需要在附件中携带excel附件,这里有两种实现方式,一种是先生成文件,然后发送附件, 一种是不借助文件直接通过流的形式发送附件,这博文主要介绍通过流的方式发送excel 附件:

1、发送邮件service

  1. package com.jack.bid.email.service;
  2. import java.io.ByteArrayInputStream;
  3. import java.security.GeneralSecurityException;
  4. import java.util.Properties;
  5. import javax.activation.DataHandler;
  6. import javax.activation.DataSource;
  7. import javax.mail.Address;
  8. import javax.mail.Authenticator;
  9. import javax.mail.Message;
  10. import javax.mail.Part;
  11. import javax.mail.PasswordAuthentication;
  12. import javax.mail.Session;
  13. import javax.mail.Transport;
  14. import javax.mail.internet.AddressException;
  15. import javax.mail.internet.InternetAddress;
  16. import javax.mail.internet.MimeBodyPart;
  17. import javax.mail.internet.MimeMessage;
  18. import javax.mail.internet.MimeMultipart;
  19. import javax.mail.internet.MimeUtility;
  20. import javax.mail.internet.MimeMessage.RecipientType;
  21. import javax.mail.util.ByteArrayDataSource;
  22. import com.sun.mail.util.MailSSLSocketFactory;
  23. import com.jack.common.utils.PropertiesUtils;
  24. import org.springframework.stereotype.Service;
  25. @Service
  26. public class BaseMail {
  27. public static Properties email = PropertiesUtils.getProperties("email.properties");
  28. public static String send_email_account = email.getProperty("send_email_account");
  29. public static String send_email_pwd = email.getProperty("send_email_pwd");
  30. public static String email_host = email.getProperty("email_host");
  31. /**
  32. * 发送邮件
  33. *
  34. * @param to 邮件收件人地址
  35. * @param title 邮件标题
  36. * @param text 内容
  37. * @param text 附件标题
  38. * @param
  39. */
  40. public void sendMsgFileDs(String to, String title, String text,String affixName, ByteArrayInputStream inputstream) {
  41. Session session = assembleSession();
  42. Message msg = new MimeMessage(session);
  43. try {
  44. msg.setFrom(new InternetAddress(send_email_account));
  45. msg.setSubject(title);
  46. msg.setRecipients(RecipientType.TO, acceptAddressList(to));
  47. MimeBodyPart contentPart = (MimeBodyPart) createContent(text, inputstream,affixName);//参数为正文内容和附件流
  48. MimeMultipart mime = new MimeMultipart("mixed");
  49. mime.addBodyPart(contentPart);
  50. msg.setContent(mime);
  51. Transport.send(msg);
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. public Address[] acceptAddressList(String acceptAddress) {
  57. // 创建邮件的接收者地址,并设置到邮件消息中
  58. Address[] tos = null;
  59. try {
  60. tos = new InternetAddress[1];
  61. tos[0] = new InternetAddress(acceptAddress);
  62. } catch (AddressException e) {
  63. // TODO Auto-generated catch block
  64. e.printStackTrace();
  65. }
  66. return tos;
  67. }
  68. public Session assembleSession() {
  69. Session session = null;
  70. Properties props = new Properties();
  71. props.setProperty("mail.smtp.auth", "true");
  72. props.setProperty("mail.transport.protocol", "smtp");
  73. props.setProperty("mail.smtp.port", "465");
  74. props.setProperty("mail.smtp.host", email_host);//邮件服务器
  75. //开启安全协议
  76. MailSSLSocketFactory sf = null;
  77. try {
  78. sf = new MailSSLSocketFactory();
  79. sf.setTrustAllHosts(true);
  80. } catch (GeneralSecurityException e1) {
  81. e1.printStackTrace();
  82. }
  83. props.put("mail.smtp.ssl.socketFactory", sf);
  84. props.put("mail.smtp.ssl.enable", "true");
  85. session = Session.getDefaultInstance(props, new MyAuthenricator(send_email_account, send_email_pwd));
  86. return session;
  87. }
  88. static Part createContent(String content, ByteArrayInputStream inputstream, String affixName) {
  89. MimeBodyPart contentPart = null;
  90. try {
  91. contentPart = new MimeBodyPart();
  92. MimeMultipart contentMultipart = new MimeMultipart("related");
  93. MimeBodyPart htmlPart = new MimeBodyPart();
  94. htmlPart.setContent(content, "text/html;charset=gbk");
  95. contentMultipart.addBodyPart(htmlPart);
  96. //附件部分
  97. MimeBodyPart excelBodyPart = new MimeBodyPart();
  98. DataSource dataSource = new ByteArrayDataSource(inputstream, "application/excel");
  99. DataHandler dataHandler = new DataHandler(dataSource);
  100. excelBodyPart.setDataHandler(dataHandler);
  101. excelBodyPart.setFileName(MimeUtility.encodeText(affixName));
  102. contentMultipart.addBodyPart(excelBodyPart);
  103. contentPart.setContent(contentMultipart);
  104. } catch (Exception e) {
  105. e.printStackTrace();
  106. }
  107. return contentPart;
  108. }
  109. //用户名密码验证,需要实现抽象类Authenticator的抽象方法PasswordAuthentication
  110. static class MyAuthenricator extends Authenticator {
  111. String u = null;
  112. String p = null;
  113. public MyAuthenricator(String u, String p) {
  114. this.u = u;
  115. this.p = p;
  116. }
  117. @Override
  118. protected PasswordAuthentication getPasswordAuthentication() {
  119. return new PasswordAuthentication(u, p);
  120. }
  121. }
  122. }

2、相关配置

  1. email_host = smtp.exmail.qq.com
  2. send_email_account=*********
  3. send_email_pwd=*******

利用ByteArrayOutputStream把excel文件输出到bytes[]中,然后由ByteArrayResource包装起来传递给邮件服务。;

3、我发送的内容就是我上篇博客中,导出的excel的内容,下面先写一个简单的测试类

  1. @Test
  2. public void sendMailWithExcel() throws IOException {
  3. @Autowired
  4. private BaseMail mailService;
  5. String[] headers = {"col1","col2","col3"};
  6. // 声明一个工作薄
  7. HSSFWorkbook wb = new HSSFWorkbook();
  8. // 生成一个表格
  9. HSSFSheet sheet = wb.createSheet();
  10. HSSFRow row = sheet.createRow(0);
  11. for (int i = 0; i < headers.length; i++) {
  12. HSSFCell cell = row.createCell(i);
  13. cell.setCellValue(headers[i]);
  14. }
  15. int rowIndex = 1;
  16. for(int j=0; j<3; j++){
  17. row = sheet.createRow(rowIndex);
  18. rowIndex++;
  19. HSSFCell cell1 = row.createCell(0);
  20. cell1.setCellValue(j);
  21. cell1 = row.createCell(1);
  22. cell1.setCellValue(j+1);
  23. cell1 = row.createCell(2);
  24. cell1.setCellValue(j+2);
  25. }
  26. for (int i = 0; i < headers.length; i++) {
  27. sheet.autoSizeColumn(i);
  28. }
  29. ByteArrayOutputStream os = new ByteArrayOutputStream(1000);
  30. wb.write(os);
  31. wb.close();
  32. ByteArrayInputStream iss = new ByteArrayInputStream(os.toByteArray());
  33. os.close();
  34. mailService.sendMsgFileDs("xjj@qq.com",
  35. "attachmentMail subject",
  36. "I have an attachment",
  37. "attachment name",
  38. iss);
  39. 注意:附件需要带后缀,例如上面例子,附件名称可以写 测试.xlsx
  40. }
  41. }

4、这样就可以 不生成中间文件直接 发送附件

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

闽ICP备14008679号