生成不保存在服务器的附件,并以附件形式发送邮件
需求:从数据库中抓取需要的数据,将数据生成excel表格,并将此表格以附件的形式放置到邮件中发送
//发送带附件的邮件,同时附件不会生成到服务器中public static String sendFileEmail(String form, String code, String to, String title, String context, Map<String,String> custBO,List<Map<String,String>> MSG) throws AddressException, MessagingException {Properties properties = new Properties();properties.put("mail.transport.protocol", "smtp");// 连接协议properties.put("mail.smtp.host", "smtp.exmail.qq.com");// 主机名properties.put("mail.smtp.port", 465);// 端口号properties.put("mail.smtp.auth", "true");properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息// 得到回话对象Session session = Session.getInstance(properties);// 获取邮件对象Message message = new MimeMessage(session);// 设置发件人邮箱地址message.setFrom(new InternetAddress(form));// 设置收件人邮箱地址message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(to) });// message.setRecipient(Message.RecipientType.TO, new// InternetAddress("xxx@qq.com"));//一个收件人// 设置邮件标题message.setSubject(title);// 设置附件// 整封邮件的MINE消息体MimeMultipart msgMultipart = new MimeMultipart("mixed");// 混合的组合关系// 设置邮件的MINE消息体message.setContent(msgMultipart);BodyPart bp = new MimeBodyPart();bp.setContent(context, "text/html;charset=gbk");msgMultipart.addBodyPart(bp);
//==================================================================================================MimeBodyPart attch = new MimeBodyPart(); // 附件msgMultipart.addBodyPart(attch); // 将附件添加到MIME消息体中ByteArrayDataSource dataSource = null; // 数据源ByteArrayOutputStream os = new ByteArrayOutputStream();HSSFWorkbook wb = new HSSFWorkbook();String deliveryNo = custBO.get("deliveryNo");// 发货订单号HSSFSheet sheet = wb.createSheet("sheet页的标题" + deliveryNo);// 设置列名HSSFRow titlerRow = sheet.createRow(0);titlerRow.createCell(0).setCellValue("新编码");titlerRow.createCell(1).setCellValue("老编码");titlerRow.createCell(2).setCellValue("数量");// 添加子表得内容for (Map<String,String> bo : MSG) {// 获取最后一行的行号int lastRowNum = sheet.getLastRowNum();HSSFRow dataRow = sheet.createRow(lastRowNum + 1);dataRow.createCell(0).setCellValue(bo.get("新编码"));dataRow.createCell(1).setCellValue(bo.get("老编码"));dataRow.createCell(2).setCellValue(bo.get("数量"));}try {wb.write(os);} catch (IOException e) {e.printStackTrace();}ByteArrayInputStream a = new ByteArrayInputStream(os.toByteArray());
//====================================================================================================Transport transport = null;try {dataSource = new ByteArrayDataSource(a, "xlsx/data");attch.setDataHandler(new DataHandler(dataSource));attch.setFileName("文件名" + ".xlsx");// 得到邮差对象transport = session.getTransport();// 连接自己的邮箱账户transport.connect(form, code);// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
// // 设置邮件内容
// message.setText(context);// 发送邮件transport.sendMessage(message, message.getAllRecipients());} catch (IOException e) {e.printStackTrace();} finally {transport.close();}return null;}