您的位置:首页 > 编程语言 > Java开发

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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  邮件