今天 突然想对现有的工程增加邮件发送功能,上网找了一些资料,结果很纳闷,邮件在发送的过程中发件人地址这里频繁的报错,没有任何验证的代码存在,试想一下实际情况,不可能我平时写什么发件人就可以发送过去了吧。后来在网上又找了些JAVA验证这一类资料,可惜,可能版本升级太快,这些方法已经无法在JAVAMAIL 1.4版里用到了,于是我在官方下了API文档,找到了这样一个方法
public static Session getInstance(java.util.Properties props, Authenticator authenticator)
每次新建会话时,我们都应该在这里填入验证明信息,让我们看看这个方法的第二个参数
public abstract class Authenticator extends java.lang.Object
这个类是抽象类,但是API文档里没有给出这个类的继承类。OK,让我们自己去继承它好了
static class SmtpAuth extends javax.mail.Authenticator {
private String user,password;
public void getuserinfo(String getuser,String getpassword){
user = getuser;
password = getpassword;
}
protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
return new javax.mail.PasswordAuthentication(user,password);
}
}
因为我图方便,我把SmtpAuth 设置成为静态内部类,看看Authenticator 的这个方法
protected PasswordAuthentication |
getPasswordAuthentication() Called when password authentication is needed. |
这就是当需要密码验证的时候此方法被呼叫,好了,返回一个PasswordAuthentication类。查出他的构造函数
PasswordAuthentication(java.lang.String userName, java.lang.String password)
Initialize a new PasswordAuthentication
于是我们可以设计username和password成员了。。于是整个验证细节也就明了拉!下面是我设计的一个简单的
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
static class SmtpAuth extends javax.mail.Authenticator {
private String user,password;
public void getuserinfo(String getuser,String getpassword){
user = getuser;
password = getpassword;
}
protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
return new javax.mail.PasswordAuthentication(user,password);
}
}
/**
* @param args
* @throws MessagingException
* @throws AddressException
*/
@SuppressWarnings("static-access")
public static void main(String[] args) throws AddressException, MessagingException {
// TODO 自动生成方法存根
Properties props = new Properties();
Session sendMailSession;
Transport transport;
SmtpAuth sa = new SmtpAuth();
sa.getuserinfo("tw", "1234");
sendMailSession = Session.getDefaultInstance(props, sa);
transport = sendMailSession.getTransport("smtp");
transport.connect("134.98.83.32","tw", "1234");
props.put("mail.smtp.host", "134.98.83.32");
props.put("mail.smtp.auth", "true");
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress("[email protected]"));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
newMessage.setSubject("hello world");
newMessage.setSentDate(new Date());
newMessage.setText("这是一个测试的例子");
transport.send(newMessage);
}
}
OK。验证成功!