java 實現郵件推送 Java實現郵件推送功能 一、引入依賴 <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.4</version> </dep ...
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