package cn.knet.data.untils.mail; import java.util.List; public class MailBean { /** * 收件人 */ private List<String> recipientsTo; /** * 抄送人 */ private List<String> recipientsCc; /** * 密送人 */ private List<String> recipientsBcc; /** * 主题 */ private String subject; /** * 正文 */ private String body; /** * 附件列表 */ private List<String> attachments; public List<String> getRecipientsTo() { return recipientsTo; } public void setRecipientsTo(List<String> recipientsTo) { this.recipientsTo = recipientsTo; } public List<String> getRecipientsCc() { return recipientsCc; } public void setRecipientsCc(List<String> recipientsCc) { this.recipientsCc = recipientsCc; } public List<String> getRecipientsBcc() { return recipientsBcc; } public void setRecipientsBcc(List<String> recipientsBcc) { this.recipientsBcc = recipientsBcc; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public List<String> getAttachments() { return attachments; } public void setAttachments(List<String> attachments) { this.attachments = attachments; } }
package cn.knet.data.untils.mail; public abstract class MailProperties { /** * SMTP服务器 */ public static final String MAIL_SMTP_HOST = "mail.smtp.host"; /** * SMTP服务器端口号 */ public static final String MAIL_SMTP_PORT = "mail.smtp.port"; /** * 登录SMTP服务器是否需要通过授权。可选值为true和false */ public static final String MAIL_SMTP_AUTH = "mail.smtp.auth"; /** * 登录SMTP服务器默认邮箱账号 */ public static final String MAIL_SMTP_SENDEMAIL = "mail.smtp.sendemail"; /** * 登录SMTP服务器默认邮箱账号 */ public static final String MAIL_SMTP_USER = "mail.smtp.user"; /** * 登录SMTP服务器默认邮箱账号对应密码 */ public static final String MAIL_SMTP_PASSWORD = "mail.smtp.password"; /** * 是否打开程序调试。可选值包括true和false */ public static final String MAIL_DEBUG = "mail.debug"; }
package cn.knet.data.untils.mail; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class MailService { private static Log logger = LogFactory.getLog(MailService.class); private static final String MAIL_PROPERTIE_NAME = "mail.properties"; private static Properties mailPro = new Properties(); private static Executor executor = Executors.newFixedThreadPool(10); static { // 初始化,读取属性文件的过程 InputStream in = null; try { in = MailService.class.getClassLoader().getResourceAsStream( MAIL_PROPERTIE_NAME); mailPro.load(in); } catch (IOException e) { if (logger.isErrorEnabled()) { logger.error(e); } } finally { if (in != null) { try { in.close(); } catch (IOException e) { if (logger.isErrorEnabled()) { logger.error(e); } } } } } public boolean sendMailText(final MailBean mail) { if (mail == null) { return false; } // 创建邮件发送任务 Runnable task = new Runnable() { @Override public void run() { final String username = mailPro .getProperty(MailProperties.MAIL_SMTP_USER); final String password = mailPro .getProperty(MailProperties.MAIL_SMTP_PASSWORD); // 创建发送邮件的会话 Session session = Session.getDefaultInstance(mailPro, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // 创建邮件消息 MimeMessage msg = new MimeMessage(session); // 设置邮件发送人 msg.setFrom(new InternetAddress(mailPro.getProperty(MailProperties.MAIL_SMTP_SENDEMAIL))); // 分别设置邮件的收件人、抄送人和密送人 msg.setRecipients(Message.RecipientType.TO, strListToInternetAddresses(mail.getRecipientsTo())); msg.setRecipients(Message.RecipientType.CC, strListToInternetAddresses(mail.getRecipientsCc())); msg.setRecipients(Message.RecipientType.BCC, strListToInternetAddresses(mail.getRecipientsBcc())); // 设置邮件主题 msg.setSubject(mail.getSubject()); msg.setSentDate(new Date());//设置邮件消息发送的时间 Multipart mp = new MimeMultipart(); // 创建邮件主体内容 MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mail.getBody()); mp.addBodyPart(mbp1); /*if (!CollectionUtils.isEmpty(mail.getAttachments())) { // 循环添加邮件附件 MimeBodyPart attach = null; for (String path : mail.getAttachments()) { attach = new MimeBodyPart(); File file = new File(path); if(file.exists()){//附件存在磁盘中 FileDataSource fds = new FileDataSource(file);//得到数据源 attach.setDataHandler(new DataHandler(fds));//得到附件本身并至入BodyPart attach.setFileName(file.getName());//得到文件名同样至入BodyPart mp.addBodyPart(attach); } } } */ if (!CollectionUtils.isEmpty(mail.getAttachments())) { // 循环添加邮件附件 MimeBodyPart attach = null; for (String path : mail.getAttachments()) { attach = new MimeBodyPart(); try { attach.attachFile(path); mp.addBodyPart(attach); } catch (IOException e) { if (logger.isErrorEnabled()) { logger.error(e); } } } } msg.setContent(mp); msg.setSentDate(new Date()); // 邮件开始发送 Transport.send(msg); } catch (AddressException e) { if (logger.isErrorEnabled()) { logger.error(e); } } catch (MessagingException e) { if (logger.isErrorEnabled()) { logger.error(e); } } } }; // 使用Executor框架的线程池执行邮件发送任务 executor.execute(task); return true; } public boolean sendMailHtml(final MailBean mail) { if (mail == null) { return false; } // 创建邮件发送任务 Runnable task = new Runnable() { @Override public void run() { final String username = mailPro .getProperty(MailProperties.MAIL_SMTP_USER); final String password = mailPro .getProperty(MailProperties.MAIL_SMTP_PASSWORD); // 创建发送邮件的会话 Session session = Session.getDefaultInstance(mailPro,new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // 创建邮件消息 MimeMessage msg = new MimeMessage(session); // 设置邮件发送人 //msg.setFrom(new InternetAddress(StringUtils.isEmpty(mail.getSender()) ? mailPro.getProperty(MailProperties.MAIL_SMTP_USER) : mail.getSender())); msg.setFrom(new InternetAddress(mailPro.getProperty(MailProperties.MAIL_SMTP_SENDEMAIL))); // 分别设置邮件的收件人、抄送人和密送人 msg.setRecipients(Message.RecipientType.TO,strListToInternetAddresses(mail.getRecipientsTo())); msg.setRecipients(Message.RecipientType.CC,strListToInternetAddresses(mail.getRecipientsCc())); msg.setRecipients(Message.RecipientType.BCC,strListToInternetAddresses(mail.getRecipientsBcc())); // 设置邮件主题 msg.setSubject(mail.getSubject()); msg.setSentDate(new Date());//设置邮件消息发送的时间 //MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含HTML内容的MimeBodyPart //设置HTML内容 messageBodyPart.setContent(mail.getBody(),"text/html; charset=utf-8"); mainPart.addBodyPart(messageBodyPart); if (!CollectionUtils.isEmpty(mail.getAttachments())) { // 循环添加邮件附件 MimeBodyPart attach = null; for (String path : mail.getAttachments()) { attach = new MimeBodyPart(); try { attach.attachFile(path); mainPart.addBodyPart(attach); } catch (IOException e) { if (logger.isErrorEnabled()) { logger.error(e); } } } } msg.setContent(mainPart); msg.setSentDate(new Date()); // 邮件开始发送 Transport.send(msg); } catch (AddressException e) { if (logger.isErrorEnabled()) { logger.error(e); } } catch (MessagingException e) { if (logger.isErrorEnabled()) { logger.error(e); } } } }; // 使用Executor框架的线程池执行邮件发送任务 executor.execute(task); return true; } /** * 将列表中的字符串转换成InternetAddress对象 * * @param list * 邮件字符串地址列表 * @return InternetAddress对象数组 */ private InternetAddress[] strListToInternetAddresses(List<String> list) { if (list == null || list.isEmpty()) { return null; } int size = list.size(); InternetAddress[] arr = new InternetAddress[size]; for (int i = 0; i < size; i++) { try { arr[i] = new InternetAddress(list.get(i)); } catch (AddressException e) { e.printStackTrace(); } } return arr; } }
mail.smtp.host=smtp.knet.cn mail.smtp.port=25 mail.smtp.auth=true mail.smtp.sendemail=sendmail@knet.cn mail.smtp.user=XXX mail.smtp.password=XXXX mail.debug=true