由于发送邮件验证性,最终测试:通过163邮箱发件级别最低,最容易发出。
需加入jar包,mail.jar
1加入参数
Properties pro = new Properties();
pro.put("mail.transport.protocol", "smtp");
pro.put("mail.smtp.host", "smtp.163.com");
pro.put("mail.smtp.auth", "true");
2.验证用户信息
Authenticator auth = new MyAuthenticator("xxx@163.com(邮箱用户名)",
"xxxxxx(邮箱密码)");
public class MyAuthenticator extends Authenticator {
private String userName = null;
private String password = null;
public MyAuthenticator(String userName,String password) {
this.userName= userName;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication passwordAuth = new PasswordAuthentication(userName,password);
return passwordAuth;
}
}
3.获得邮件会话
Session sesion = Session.getInstance(pro, auth);
SMTPTransport trans = null;
try {
trans = (SMTPTransport) sesion.getTransport("smtp");
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
4.创建消息
Message msg = new MimeMessage(sesion);
try {
msg.setFrom(new InternetAddress("xxx@163.com"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("接收邮箱地址如,xxx@qq.com", true));
msg.setSentDate(new Date());
msg.setSubject("邮箱验证");
String url="http://www.baidu.com/shop/active!activeEmail.do?ccc=aaa";//回调项目地址即激活路径,根据需求而设计
try {
url=LongUrlToShortUrl.longUrlToShortUrl(url);//长地址转短地址,可忽略不计
} catch (Exception e) {
e.printStackTrace();
}
msg.setText("点击以下链接,激活账号;"+url);
} catch (MessagingException e) {
e.printStackTrace();
}
5.发送邮件
try {
trans.connect("smtp.163.com", "xxx@163.com(邮箱用户名)", "xxxxxx(邮箱密码)");
trans.sendMessage(msg, msg.getAllRecipients());
} catch (MessagingException e) {
e.printStackTrace();
}