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

配置文件:

文件名称:mail.properties

mail.smtp.host=smtp.163.com
mail.smtp.port=25
mail.smtp.auth=true
mail.transport.protocol=smtp
userName=xxx@163.com
password=授权码
sendNo=xxx@163.com

工具类:

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<String> to, List<String> cc, List<File> 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<String> to, List<String> cc, List<File> 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;
	}
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值