MailUtil.java
package com.lucky.base.common.util;
import com.zuche.framework.utils.PropertiesReader;
import org.apache.commons.mail.HtmlEmail;
import javax.mail.internet.InternetAddress;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 发送邮件
* Created by dongdong.shi@ucarinc.com on 2017/7/29.
*/
public final class MailUtil {
/**
* 邮件配置
*/
private static final Properties CONFIG = PropertiesReader.getProperties("mail");
/**
* 默认编码
*/
private static final String UTF8 = "utf-8";
/**
* 域名
*/
private static String DOMAIN = CONFIG.getProperty("mail.domain");
/**
* 发送服务器地址
*/
private static String HOST = CONFIG.getProperty("mail.host");
/**
* 发送端口
*/
private static String PORT = CONFIG.getProperty("mail.port");
/**
* 用户名
*/
private static String USER = CONFIG.getProperty("mail.user");
/**
* 密码
*/
private static String PASSWORD = CONFIG.getProperty("mail.password");
/**
* 发送者
*/
private static String SENDER = CONFIG.getProperty("mail.sender");
/**
* 获取邮件domain
* @return 返回domain
*/
public static String getMailDomain() {
return DOMAIN;
}
/**
* 获取admin的邮箱
* @return admin邮箱地址
*/
public static String getAdminMail() {
return USER+"@"+DOMAIN;
}
/**
* 发送邮件
* @param receives 收件人,多个收件人以;隔开
* @param subject 邮件主题
* @param msg 邮件内容
* @throws Exception 发送邮件异常
*/
public static void send(String receives, String subject, String msg) throws Exception {
HtmlEmail htmlEmail = new HtmlEmail();
htmlEmail.setHostName(HOST);
htmlEmail.setSmtpPort(Integer.parseInt(PORT));
htmlEmail.setAuthentication(USER, PASSWORD);
htmlEmail.setFrom(SENDER);
htmlEmail.setTo(getSendAddressList(receives));
htmlEmail.setCharset(UTF8);
htmlEmail.setSubject(subject);
htmlEmail.setMsg(msg);
htmlEmail.send();
}
/**
* 格式化邮件内容
* @param template 邮件模板
* @param args 参数
* @return 返回实际的邮件内容
*/
public static String format(String template, String[] args) {
MessageFormat format = new MessageFormat(template);
return format.format(args);
}
/**
* 组装收件人
* @param receives 收件人
* @return 真实的收件人地址
* @throws Exception 拼装邮件地址异常
*/
private static List<InternetAddress> getSendAddressList(String receives) throws Exception {
List<InternetAddress> addressList = new ArrayList<InternetAddress>();
String[] tokens = receives.split(";");
for(String address : tokens) {
addressList.add(new InternetAddress(address));
}
return addressList;
}
}
#配置文件#
mail.domain=luckycoffee.com
mail.host=mail.luckycoffee.com
mail.port=25
mail.user=sysadmin
mail.password=lucky_admin_2017
mail.sender=sysadmin@luckycoffee.com
mail.properties
mail.domain=luckycoffee.com
mail.host=mail.luckycoffee.com
mail.port=25
mail.user=sysadmin
mail.password=lucky_admin_2017
mail.sender=sysadmin@luckycoffee.com