java 定时发送邮件以及数据导出excel作为附件
2017-06-16 15:28
615 查看
定时发送邮件以及数据导出excel作为附件
这次要求每天定时统计前一天的领券名单,结果导出成excel并且自动发送邮件使用 ScheduledExecutorService 实现
Maven
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.5.0-b01</version> </dependency> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.5.7</version> </dependency>
定时器设置
然后放入监听中MailUtil.init();public static void init() { ScheduledExecutorService pool = Executors.newScheduledThreadPool(1); long oneDay = 24 * 60 * 60 * 1000; long initDelay = TimeUtil.getTimeMillis("02:17:00") - System.currentTimeMillis(); initDelay = initDelay > 0 ? initDelay : oneDay + initDelay; pool.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { String to = ConfigLoader.getInstance().getProperty("MAIL_TO"); String subject = ConfigLoader.getInstance().getProperty("MAIL_SUBJECT"); long startTime = TimeUtil.getStartTime(); long endTime = TimeUtil.getEndTime(); logger.info("startTime = " + startTime + " endTime = " + endTime); List<DataEntity> list = dao.queryMobileList(startTime, endTime); long time = System.currentTimeMillis() - 60 * 60 * 24 * 1000; SimpleDateFormat formatter = new SimpleDateFormat("MMdd"); subject = formatter.format(time) + subject; String filePath = exportExcel(list, formatter.format(time)); List<File> fList = new Vector<File>(); fList.add(new File(filePath)); MailUtil.send(to, subject, subject, fList); } catch (Throwable t) { logger.error(" sendEmail fail "); } } }, initDelay, oneDay, TimeUnit.MILLISECONDS); }
数据导出Excel
public static String exportExcel(List<DataEntity> list, String fileName) throws IOException { WritableWorkbook wwb = null; File file = new File(PATH + fileName + ".xls"); if (!file.exists()) { file.createNewFile(); } wwb = Workbook.createWorkbook(file); WritableSheet ws = wwb.createSheet("***名单", 0); Label labelId = new Label(0, 0, "序号"); Label labelMobile = new Label(1, 0, "手机号"); Label labelIp = new Label(2, 0, "ip地址"); try { ws.addCell(labelId); ws.addCell(labelMobile); ws.addCell(labelIp); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } for (int i = 0; i < list.size(); i++) { Label labelId_i = new Label(0, i + 1, list.get(i).getId() + ""); Label labelMobile_i = new Label(1, i + 1, list.get(i).getMobile()); Label labelIp_i = new Label(2, i + 1, list.get(i).getIp()); try { ws.addCell(labelId_i); ws.addCell(labelMobile_i); ws.addCell(labelIp_i); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } wwb.write(); try { wwb.close(); } catch (WriteException e) { e.printStackTrace(); } return PATH + fileName + ".xls"; }
发送邮件
public static void send(String to, String subject, String body, List<File> files) throws Exception { List<InternetAddress> addresses = new Vector<InternetAddress>(); if (StringUtil.isNotNull(to)) { String[] arr = to.trim().split(","); for (String str : arr) { if (StringUtil.isNotNull(str)) { addresses.add(new InternetAddress(str.trim())); } } } if (addresses.isEmpty()) { throw new Exception("None receiver! The program will be exit!"); } if (StringUtil.isNull(subject)) { subject = "This is a Default Subject"; } List<MimeBodyPart> mbps = new Vector<MimeBodyPart>(); if (files != null && !files.isEmpty()) { for (File f : files) { if (!f.exists()) continue; MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f.getAbsolutePath()); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(MimeUtility.encodeText(fds.getName())); mbps.add(mbp); } } if (body == "" a70a || body == null) body = ""; logger.info("subject = " + subject + " body = " + body + " addresses = " + addresses); sendMail(subject, body, addresses, mbps); } private static void sendMail(String subject, String body, List<InternetAddress> addresses, List<MimeBodyPart> mbps) throws Exception { String host = ConfigLoader.getInstance().getProperty("SMTP_HOST"); String userName = ConfigLoader.getInstance().getProperty("SMTP_USER"); String password = ConfigLoader.getInstance().getProperty("SMTP_PASSWORD"); String userMail = ConfigLoader.getInstance().getProperty("SMTP_MAIL"); if (StringUtil.isNull(host) || StringUtil.isNull(userName) || StringUtil.isNull(password) || StringUtil.isNull(userMail)) throw new Exception( "Invalid params : " + host + "," + userName + "," + password + "," + userMail); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(userMail)); msg.addRecipients(Message.RecipientType.TO, addresses.toArray(new InternetAddress[] {})); msg.setSubject(subject); msg.setSentDate(new Date()); if (mbps.isEmpty()) { msg.setText(body); } else { Multipart mp = new MimeMultipart(); for (MimeBodyPart part : mbps) { mp.addBodyPart(part); } if (StringUtil.isNotNull(body)) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); mp.addBodyPart(messageBodyPart); } msg.setContent(mp); } msg.saveChanges(); int maxRetries = 10; int retryCount = 0; while (true) { try { Transport transport = session.getTransport("smtp"); transport.connect(host, userName, password); transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO)); transport.close(); break; } catch (Exception e) { if (e instanceof SocketException && retryCount < maxRetries) { retryCount++; logger.error("send mail {} failed {}, {} ", subject, retryCount, e.getMessage()); continue; } throw e; } } }
相关文章推荐
- Java实现通过poi把数据查出来放在模板Excel中并作为附件发送邮件
- 在java中 发送邮件 以及定时发送 以及 发送多附件项目下载
- JAVA 写Excel附件 每天定时发送邮件
- JAVA 写Excel附件 每天定时发送邮件
- SQL Server 定时发送邮件(从数据库查询出的数据作为附件)
- JAVA 写Excel附件 每天定时发送邮件
- Java程序员从笨鸟到菜鸟之(一百零五)java操作office和pdf文件(三)利用jxl实现数据导出excel报表以及与POI的区别
- Android向Excel写入数据导出U盘并发送邮件
- 基于javaMail的邮件发送--excel作为附件
- JavaPoi技术二-------导出数据到Excel以及从excel中读取数据
- 将从数据库导出的数据以excel的附件形势发送到指定邮箱
- 超简单的Java定时发送带附件邮件
- java发送邮件可带附件,以及发送网页等
- delhi从数据库导出数据生成Excel并自动发送邮件笔记
- Java程序员从笨鸟到菜鸟之(一百零五)java操作office和pdf文件(三)利用jxl实现数据导出excel报表以及与POI的区别
- java实现excel横排以及竖排数据导出
- java POI导出excel(带有图片的数据)以及ftp上传图片到另一台服务器的方法参考代码
- 导出mysql数据,利用pandas生成excel文档,并发送邮件
- java 发送邮件(qq邮箱作为发件箱,带附件)