1. 程式人生 > >基於apache-commons-email1.4 郵件傳送

基於apache-commons-email1.4 郵件傳送


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 
[email protected]
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
[email protected]


mail.properties


mail.domain=luckycoffee.com
mail.host=mail.luckycoffee.com
mail.port=25
mail.user=sysadmin
mail.password=lucky_admin_2017
[email protected]