用java代码发送邮件(优化版)
程序员文章站
2024-01-07 15:29:10
...
调用代码如下:
代码如下:
if(!StringUtil.isNullOrEmpty(address)){ SendEmailUtil.sendEmail(globalProperties.getEmailSubject() , noticeMsg.toString() , address , globalProperties.getEmailIsSend(), globalProperties.getEmailAccount() , globalProperties.getEmailPassword() , globalProperties.getEmailFromAddress() , globalProperties.getEmailHost() , globalProperties.getEmailPort()); }else{ this.logger.debug("重置密码时,邮件无法发送,原因为:账户邮箱地址为空"); }
代码如下:
package com.banger.ubip.common.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.Properties; import java.util.StringTokenizer; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; 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.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.*; /** * @Author luozx * @Date 2016/12/26 10:20. */ public class SendEmailUtil extends Authenticator implements Runnable{ private static final boolean validate = true; private String subject; private String account; private String password; private String fromAddress; private String msg; private String address; private Properties pro = new Properties(); private static Session sendMailSession = null; private String emailIsSend;//邮件是否发送的开关 true为发送邮件 protected Logger logger = LoggerFactory.getLogger(getClass()); //邮件发送的线程池 private static ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 200, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10)); public static void sendEmail(String subject , String msg , String address , String emailIsSend , String account, String password, String fromAddress, String host, String port) { SendEmailUtil set = new SendEmailUtil(subject , msg , address , emailIsSend ,account, password, fromAddress, host, port); executor.execute(set); } public SendEmailUtil(String subject , String msg , String address , String emailIsSend , String account, String password, String fromAddress, String host, String port) { super(); this.subject = subject; this.account = account; this.password = password; this.fromAddress = fromAddress; this.msg = msg; this.address = address; this.emailIsSend = emailIsSend; pro.put("mail.smtp.host",host); pro.put("mail.smtp.port",port); pro.put("mail.smtp.auth", validate ? "true" : "false"); } @Override public void run() { if(!StringUtil.isNullOrEmpty(emailIsSend) && "true".equals(emailIsSend)){ InternetAddress[] ia = parseAddress(address); sendTextMail(ia,subject,msg); logger.info("邮件发送完成,接收者为:[{}]",address); } } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(account, password); } /** * 以文本格式发送邮件 * * @param ToAddress * @param Subject * @param Content * 待发送的邮件的信息 */ public boolean sendTextMail(InternetAddress[] ToAddress, String Subject, String Content) { // 判断是否需要身份认证 try { // 根据邮件会话属性和密码验证器构造一个发送邮件的session // Session sendMailSession = Session.getDefaultInstance(pro, this); if (sendMailSession == null) { sendMailSession = Session.getDefaultInstance(pro, this); } // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(fromAddress); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 if (ToAddress.length == 1) { mailMessage.setRecipients(Message.RecipientType.TO, ToAddress); } else { mailMessage.setRecipients(Message.RecipientType.BCC, ToAddress); } // 设置邮件消息的主题 mailMessage.setSubject(MimeUtility.encodeText(Subject,MimeUtility.mimeCharset("utf-8"), null)); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 // mailMessage.setText(Content); mailMessage.setContent(Content, "text/html;charset=utf-8"); // 发送邮件 Transport.send(mailMessage); return true; } catch (Exception ex) { logger.error("邮件发送异常,[{}]",ex); } return false; } /** * 以HTML格式发送邮件 * * @param ToAddress * @param Subject * @param Content * 待发送的邮件信息 */ public boolean sendHtmlMail(InternetAddress[] ToAddress, String Subject, String Content) { try { // 根据邮件会话属性和密码验证器构造一个发送邮件的session // Session sendMailSession = Session.getDefaultInstance(pro, this); if (sendMailSession == null) { sendMailSession = Session.getDefaultInstance(pro, this); } // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(fromAddress); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 // Message.RecipientType.TO属性表示接收者的类型为TO if (ToAddress.length == 1) { mailMessage.setRecipients(Message.RecipientType.TO, ToAddress); } else { mailMessage.setRecipients(Message.RecipientType.BCC, ToAddress); } // 设置邮件消息的主题 mailMessage.setSubject(Subject); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 设置HTML内容 html.setContent(Content, "text/html; charset=utf-8"); mainPart.addBodyPart(html); // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { logger.error("邮件发送异常,[{}]",ex); } return false; } public InternetAddress[] parseAddress(String addr) { StringTokenizer token = new StringTokenizer(addr, ","); InternetAddress[] addrArr = new InternetAddress[token.countTokens()]; int i = 0; while (token.hasMoreTokens()) { try { addrArr[i] = new InternetAddress(token.nextToken().toString()); } catch (AddressException e1) { return null; } i++; } return addrArr; } public static void main(String[] args) { String subject = "系统通知邮件"; String noticeMsg = "这是一封神奇的邮件"; String address = "7184638022@qq.com"; String emailIsSend = "true"; String accountTemp = "123123@qq.com"; String passwordTemp = "123456"; String fromAddressTemp = "123123@qq.com"; String hostTemp = "smtp.exmail.qq.com"; String portTemp = "25"; SendEmailUtil set = new SendEmailUtil(subject , noticeMsg , address , emailIsSend , accountTemp , passwordTemp , fromAddressTemp , hostTemp,portTemp); set.run(); } }