Java实现邮件推送功能

java 实现邮件推送

Java实现邮件推送功能

一、引入依赖

 <dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-email</artifactId>
           <version>1.4</version>
</dependency>

二、邮件来源用户信息

private static Logger log = Log.getLogger();
private static ThreadPoolExecutor threadPool;
private static String emailServer;
private static String userName;
private static String password;
private static String emailEncoding;
private static String emailFrom;
private static String sysEmailFromName;
private static String encoding;

private static void initMail(Email mail) throws EmailException {
mail.setHostName(emailServer);
mail.setAuthentication(userName, password);
mail.setCharset(emailEncoding);
mail.setFrom(emailFrom, sysEmailFromName);
}

三、线程池异步

static {
threadPool = new ThreadPoolExecutor(5, 10, 3L, TimeUnit.SECONDS, new ArrayBlockingQueue(50), new ThreadPoolExecutor.DiscardPolicy());
//邮箱服务器地址
emailServer = "smtp.163.com";
//用户名
userName = "****";
//用户密码
password = "****";
//编码格式
emailEncoding = "GBK";
//邮件来源
emailFrom = "*****.com.cn";
//邮件来源用户名称
sysEmailFromName = "****";
//编码格式
encoding = "UTF-8";
}

四、异步发送

 private static void sendMail(Email mail) {
      threadPool.execute(new Runnable() {
          @Override
          public void run() {
              try {
                  mail.send();
              } catch (EmailException var2) {
                  log.error("[邮件抄送失败]-", var2);
              }
          }
      });
  }

五 完整发送

import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.*;
import org.slf4j.Logger;

import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* 邮件发送工具
*/
public class MailUtil {

private static Logger log = Log.getLogger();
   private static ThreadPoolExecutor threadPool;
   private static String emailServer;
   private static String userName;
   private static String password;
   private static String emailEncoding;
   private static String emailFrom;
   private static String sysEmailFromName;
   private static String encoding;
   
   private static void initMail(Email mail) throws EmailException {
       mail.setHostName(emailServer);
       mail.setAuthentication(userName, password);
       mail.setCharset(emailEncoding);
       mail.setFrom(emailFrom, sysEmailFromName);
  }
   
   static {
threadPool = new ThreadPoolExecutor(5, 10, 3L, TimeUnit.SECONDS,
                                       new ArrayBlockingQueue(50),
                                       new ThreadPoolExecutor.DiscardPolicy());
//邮箱服务器地址
emailServer = "mailha.sinosafe.local";
//用户名
userName = "****";
//用户密码
password = "****";
//编码格式
emailEncoding = "GBK";
//邮件来源
emailFrom = "*****.com.cn";
//邮件来源用户名称
sysEmailFromName = "****";
//编码格式
encoding = "UTF-8";
}
   
    /**
    * 异步发送邮件
    */
   private static void sendMail(Email mail) {
       threadPool.execute(new Runnable() {
           @Override
           public void run() {
               try {
                   mail.send();
              } catch (EmailException var2) {
                   log.error("[邮件抄送失败]-", var2);
              }
          }
      });
  }
   
   /**
   * 抄送郵件
   */
   public static void bccHtmlEmail(String subject, String html, List<String> users) throws Exception {
       HtmlEmail email = new HtmlEmail();
       initMail(email);
       email.setSubject(subject);
       for (String r : users){
           email.addBcc(r);
}
       email.setHtmlMsg(html);
       email.setTextMsg("Your email client does not support HTML messages");
       sendMail(email);
  }
   
   /**
   * 单附件邮件
   */
   public static void sendEmailWithFile(String subject, String html, List<String> receivers,
                                        File file) throws UnsupportedEncodingException {
       //附件
       EmailAttachment att1 = new EmailAttachment();
       att1.setPath(file.getPath());
       att1.setDisposition(EmailAttachment.ATTACHMENT);
       att1.setDescription("attachemnt description gril 中文");
       att1.setName(MimeUtility.encodeText(file.getName()));
       MultiPartEmail email = new MultiPartEmail();
       email.setHostName(emailServer);
       email.setAuthentication(userName, password);
       email.setCharset(emailEncoding);
       email.setSubject(subject);
       try {
           email.setMsg(html);
           for (String user : receivers) {
               email.addTo(user);
          }
           email.setFrom(emailFrom, sysEmailFromName);
           email.attach(att1);  
           email.send();
      } catch (EmailException e1) {
           e1.printStackTrace();
      }
  }
   
   public static void sendEmailMultifile(String subject, String html, List<String> receivers,
                                         List<File> files){
       HtmlEmail email = new HtmlEmail();
       email.setHostName(emailServer);
       email.setAuthentication(userName, password);
       email.setCharset(emailEncoding);
       email.setSubject(subject);
       try {
           for (String user : receivers) {
               email.addTo(user);
          }
           email.setFrom(emailFrom, sysEmailFromName);
           email.setHtmlMsg(html);
           //附件
           for(File f : files){
               EmailAttachment att1 = new EmailAttachment();
               att1.setPath(f.getPath());
               att1.setDisposition(EmailAttachment.ATTACHMENT);
               att1.setDescription("attachemnt description gril 中文"); //附件描述
               //防止附件名乱码
               att1.setName(MimeUtility.encodeText(f.getName()));
               email.attach(att1);
          }
           email.send();
      }catch (EmailException | UnsupportedEncodingException e1) {
           e1.printStackTrace();
      }
  }
   
   /**
   * 抄送郵件
   */
  public static void ccHtmlEmail(String subject, String html, String receiver, String cc)
           throws Exception {
       ccHtmlEmail(subject, html, Arrays.asList(receiver.split(",")), cc, null);
  }

   /**
   * 抄送郵件带附件
   */
   public static void ccHtmlEmail(String subject, String html, String receiver, String cc, File file)
       throws Exception {
       ccHtmlEmail(subject, html, Arrays.asList(receiver.split(",")), cc, file);
  }

}

五、总结

Java实现邮件发送,可以异步使用线程池批量发送多人,减小服务器的压力,可以发送单页面(可以是html语言写的页面),也可以单附件或者多附件发送邮件。

热门相关:惊悚乐园   九阳剑圣   纣临   万妖帝主   绝宠小医妃:王爷,来一针