帮蕊姐姐完成一个任务,给几百号人发邮件,索性把以前写过的Javamail和读excel的代码调通了。下面简单记录一下。
Java发送邮件
MyAuthenticator.java
package com.umgsai.mail; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MyAuthenticator extends Authenticator{ String userName = null; String password = null; public MyAuthenticator() { } public MyAuthenticator(String username, String password) { this.userName = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }
MailSenderInfo.java
package com.umgsai.mail; import java.util.Properties; public class MailSenderInfo { // 发送邮件的服务器的IP和端口 private String mailServerHost; private String mailServerPort = "25"; // 邮件发送者的地址 private String fromAddress; // 邮件接收者的地址 private String toAddress; // 登陆邮件发送服务器的用户名和密码 private String userName; private String password; // 是否需要身份验证 private boolean validate = false; // 邮件主题 private String subject; // 邮件的文本内容 private String content; // 邮件附件的文件名 private String[] attachFileNames; /** * 获得邮件会话属性 */ public Properties getProperties() { Properties p = new Properties(); p.put("mail.smtp.host", this.mailServerHost); p.put("mail.smtp.port", this.mailServerPort); p.put("mail.smtp.auth", validate ? "true" : "false"); return p; } public boolean isValidate() { return validate; } //省略getter setter }
SimpleMailSender.java
package com.umgsai.mail; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SimpleMailSender { /** * 以文本格式发送邮件 * @param mailInfo 待发送的邮件的信息 */ public boolean sendTextMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session //Session.ge Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * 以HTML格式发送邮件 * @param mailInfo 待发送的邮件信息 */ public static boolean sendHtmlMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); //如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session // Session.getInstance(pro, authenticator) Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 设置HTML内容 html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } }
测试主类 Main.java
package com.umgsai.mail; import java.io.IOException; import java.util.List; import com.zappinfo.test.XlsMain; public class Main { public static void main(String[] args) { //这个类主要是设置邮件 MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.163.com"); mailInfo.setMailServerPort("25"); mailInfo.setValidate(true); //设置发送邮箱和接收邮箱 mailInfo.setUserName("***@163.com"); mailInfo.setPassword("***");//您的邮箱密码 mailInfo.setFromAddress("***@163.com"); // mailInfo.setToAddress("***@qq.com"); mailInfo.setToAddress("***"); mailInfo.setSubject("测试标题"); mailInfo.setContent("设置邮箱内容 测试"); //这个类主要来发送邮件 SimpleMailSender sms = new SimpleMailSender(); /* * sms.sendTextMail(mailInfo);//发送文体格式 sms.sendHtmlMail(mailInfo);//发送html格式 */ //下面为读取excel数据然后发送 XlsMain xlsMain = new XlsMain(); try { List<String []> list = xlsMain.readXls(); String [] title0 = list.get(0); String [] title1 = list.get(1); for(int i = 2; i < 24; i++){ String [] s = list.get(i); StringBuilder sb = new StringBuilder(); for(int j = 0; j < 20; j++){ if(j == 0){ continue; } if(!title0[j].equals("0.0")){ sb.append("<br/>----" + title0[j] + "----<br/>"); System.err.println("<br/>----" + title0[j] + "----"); } if(!title1[j].equals("0.0")){ sb.append(title1[j] + ":"); System.err.print(title1[j] + ":"); } sb.append(s[j] + "\t<br/>"); System.err.print(s[j] + "\t<br/>"); } sb.append("<br/>本邮件由系统自动发送,实际工资发放以工资条为准!<br/>"); System.out.print("<br/>本邮件由系统自动发送,实际工资发放以工资条为准!<br/>"); sb.append("<br/>有疑问请联系:蒋蕊 [email protected] 027-5066-2279!<br/>"); sb.append("<br/><font color='red'>系统邮件,请勿直接回复!</font><br/>"); sb.append("<br/><font color='red'>@"+ s[3] +"!</font><br/>"); mailInfo.setSubject(s[1] + "-" + s[2] + "-工资信息"); mailInfo.setContent(sb.toString()); sms.sendHtmlMail(mailInfo);//发送文体格式 } } catch (IOException e) { e.printStackTrace(); } } }
2.Java读取excel
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; //参考 http://www.cnblogs.com/hongten/archive/2012/02/22/java2poi.html public class XlsMain { public static void main(String[] args) { XlsMain xlsMain = new XlsMain(); try { List<String []> list = xlsMain.readXls(); // System.err.println(list); System.err.println("--------------------------"); int k = 0; for (Iterator iterator = list.iterator(); iterator.hasNext();) { String[] strings = (String[]) iterator.next(); for (int i = 0; i < strings.length; i++) { if(strings[i] != null){ System.err.print(strings[i] + " "); } } System.out.print("\n"); k++; if(k == 3){ break; } } System.err.println("--------------------------"); } catch (IOException e) { e.printStackTrace(); } } public String getValue(HSSFCell hssfCell) { if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) { // 返回布尔类型的值 return String.valueOf(hssfCell.getBooleanCellValue()); } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) { // 返回数值类型的值 return String.valueOf(hssfCell.getNumericCellValue()); } else { // 返回字符串类型的值 return String.valueOf(hssfCell.getStringCellValue()); } } public String getValue(Cell cell) { DecimalFormat df = new DecimalFormat("######0.00"); if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) { // 返回布尔类型的值 return String.valueOf(cell.getBooleanCellValue()); } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) { // 返回数值类型的值 // return String.valueOf(cell.getNumericCellValue()); return String.valueOf(df.format(cell.getNumericCellValue())); } else if(cell.getCellType() == cell.CELL_TYPE_BLANK){ return "0.0"; }else if(cell.getCellType() == cell.CELL_TYPE_ERROR){ return "0"; }else if(cell.getCellType() == cell.CELL_TYPE_FORMULA){ // return ""; // return String.valueOf(cell.getNumericCellValue()); return String.valueOf(df.format(cell.getNumericCellValue())); }else{ // 返回字符串类型的值 return String.valueOf(cell.getStringCellValue()); } } public List<String []> readXls() throws IOException { InputStream is = new FileInputStream("D:/AliDrive/我的文档/总公司6月工资工资单.xls"); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); XlsDto xlsDto = null; List<String []> list = new ArrayList<String []>(); // 循环工作表Sheet for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 循环行Row for (int rowNum = 0; rowNum < hssfSheet.getLastRowNum(); rowNum++) { String[] str = new String[1000]; System.err.print(rowNum + "\t"); HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow == null) { continue; } // 循环列Cell Iterator<Cell> cellIterator = hssfRow.cellIterator(); int k = 0; while (cellIterator.hasNext()) { Cell cell = (Cell) cellIterator.next(); System.out.print(getValue(cell)+"\t\t"); str[k++] = getValue(cell); } System.out.print("\n"); list.add(str); } } return list; } }
读取xlsx格式的excel存在问题,暂未深入研究。
暂未考虑性能优化,大神请略过~~
PS:源码在蕊姐姐邮箱