需要使用commons-email-1.2.jar 和email必备的jar包
/** * 获取中文设置的发件人 * @param sender * @return * @throws UnsupportedEncodingException */ private static String getSenderZh(String sender) throws UnsupportedEncodingException { if (sender != null && !sender.trim().equals("")) { return new String(sender.getBytes("iso-8859-1"), "utf-8"); } else { return "XX网"; } }
批量发送邮件:
/*** * 功能:批量发送邮件 * @param toEmail :接收邮箱 * @param subject :主题 * @param body :邮件内容 */ public static void send(Collection<String> emailCo, String subject, String body) throws EmailException, Exception { HtmlEmail email = new HtmlEmail(); email.setHostName(proInfo.getProperty("send_host"));// 设置发信的smtp服务器 for (String toEmail : emailCo) { toEmail = toEmail.trim(); email.addTo(toEmail, getUserByEmail(toEmail));// 设置收件人帐号和收件人 } email.setFrom(proInfo.getProperty("send_user_email"), getSenderZh(proInfo.getProperty("send_user_zh")));// 设置发信的邮件帐号和发信人 email.setSubject(subject);// 设置邮件主题 email.setAuthentication(proInfo.getProperty("send_user"), proInfo .getProperty("send_password"));// 如果smtp服务器需要认证的话,在这里设置帐号、密码 if(proInfo.getProperty("send_port")!=null){//设置smtp端口 email.setSSL(true); email.setSmtpPort(Integer.parseInt(proInfo.getProperty("send_port"))); } email.setCharset("utf-8"); email.setHtmlMsg(body);// 设置邮件正文和字符编码 email.send(); }
资源文件:
send_host=smtp邮箱服务器
send_user_email=发件人邮箱地址
send_user=权限
send_password=密码
send_user_zh=中文发件人
// 资源文件名称 private static final String smsPropFile = "email.properties"; static { try { InputStream in = MailSend.class.getClassLoader() .getResourceAsStream(smsPropFile); proInfo.load(in); in.close(); } catch (Exception e) { System.err.print("邮件发送配置文件加载失败..."); } }