javamail邮件心得(二)之邮件验证

一、写一个验证类,并且继承Authenticator类,如下

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class SmtpAuth extends Authenticator {
	String username;

	String pwd;

	public SmtpAuth(String username, String pwd) {
		this.username = username;
		this.pwd = pwd;
	}

	public PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, pwd);
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
}

 二、登陆验证,具体代码如下

Properties props = getProps();//此方法上篇文章有,获取属性文件信息
SmtpAuth auth = new SmtpAuth(user.getName(), user.getPwd());//传入用户名和密码
Session session = Session.getDefaultInstance(props, auth);//进行验证
Store store = session.getStore("imap");
store.connect("imap地址", "用户名" "密码");

 以上代码可以放到try里,如出现异常则登陆失败,可存储日志

 

注:此处登陆可将用户信息放到session中,登陆成功后也可将Store对象放到session中,这样以后可以不必每次都进行验证

你可能感兴趣的:(javamail)