Java-发送邮件-工具类和配置文件

配置文件:

文件名称:mail.properties

mail.smtp.host=smtp.163.com
mail.smtp.port=25
mail.smtp.auth=true
mail.transport.protocol=smtp
[email protected]
password=授权码
[email protected]

工具类:

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.polarion.core.util.logging.Logger;

/**
 * @created 2019年1月21日 下午4:09:33
 */
public class EmailUtil {
	// 日志记录
	private static Logger logger = Logger.getLogger(EmailUtil.class);

	public static MailAuthenticator authenticator;
	private MimeMessage message;
	private Session session;
	private Properties properties = new Properties();

    private String sender_username = null;
    private String sender_password = null;


	/**
	 * 构造方法
	 */
	public EmailUtil() {
		super();
	}

	/**
	 * 供外界调用的发送邮件接口
	 */
	public boolean sendEmail(String title, String content, List to, List cc, List fileList) {
		try {
			// 初始化smtp发送邮件所需参数
			initSmtpParams();
			// 发送邮件
			doSendHtmlEmail(title, content, to, cc, fileList);

		} catch (Exception e) {
			logger.error(e);
		}
		return true;
	}

	/**
	 * 初始化smtp发送邮件所需参数
	 */
	private boolean initSmtpParams() {
		InputStream inputStream =  null;
		try {
			inputStream =  this.getClass().getClassLoader().getResourceAsStream("mail.properties");
			properties = new Properties();
			properties.load(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
        sender_username = properties.getProperty("userName");
        sender_password = properties.getProperty("password");
        authenticator = new MailAuthenticator(sender_username, sender_password);
		session = Session.getDefaultInstance(properties, authenticator);
		session.setDebug(true);// 开启后有调试信息
		message = new MimeMessage(session);

		return true;
	}

	/**
	 * 发送邮件
	 */
	private boolean doSendHtmlEmail(String title, String htmlContent, List to, List cc, List fileList) {
		try {
			// 发件人
			InternetAddress from = new InternetAddress(properties.getProperty("sendNo"));
			message.setFrom(from);

			// 收件人(多个)
			InternetAddress[] toAddress = new InternetAddress[to.size()];
			for (int i = 0; i < to.size(); i++) {
				toAddress[i] = new InternetAddress(to.get(i));
			}
			message.setRecipients(MimeMessage.RecipientType.TO, toAddress);
			// 抄送人(多个)
			if(cc != null && cc.size() > 0){
				InternetAddress[] ccAddress = new InternetAddress[cc.size()];
				for (int i = 0; i < cc.size(); i++) {
					ccAddress[i] = new InternetAddress(cc.get(i));
				}
				message.setRecipients(MimeMessage.RecipientType.CC, ccAddress);
			}
			// 邮件主题
			message.setSubject(title);
			// 设置邮件消息发送的时间    
			message.setSentDate(new Date());
			message.setContent(htmlContent, "text/html; charset=utf-8");  
			// 保存邮件
			message.saveChanges();
			// 发送邮件
			Transport.send(message);
			System.out.println(title + " Email send success!");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return true;
	}
}
/**
 * 
 * @author ThinkPad
 *
 */
class MailAuthenticator extends Authenticator {
	private String userName;
	private String password;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@SuppressWarnings("restriction")
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(userName, password);
	}

	public MailAuthenticator(String username, String password) {
		this.userName = username;
		this.password = password;
	}
}

 

你可能感兴趣的:(Java)