package com.robin;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
public class main{
private static final String SMTP_HOST_NAME = "";
private static final String SMTP_AUTH_USER = "";
private static final String SMTP_AUTH_PWD = "";
public static void main(String[] args) throws Exception{
new main().test();
}
public void test() throws Exception{
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "2525");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
// uncomment for debugging infos to stdout
// mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setContent("This is a test", "text/plain");
message.setFrom(new InternetAddress(""));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(""));
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
是什么使新对象(Authenticator auth = new SMTPAuthenticator();
(正在运行getPasswordAuthentication()
方法,尽管它不是构造函数?
通常,如果我们创建一个对象,它的构造函数会运行,但此方法不是构造函数。我对这段代码感到非常困惑。任何帮助,不胜感激。
这是构造函数链接。
构造函数链接通过使用继承发生。子类构造函数方法的第一个任务是调用其超类的构造函数方法。
首先,基类的构造函数将运行,然后仅运行子类或派生类的构造函数。
由于您扩展了类javax.mail.Authenticator
,因此会自动调用构造函数
来自javax.mail.Authenticator的JavaDocs
http://docs.oracle.com/javaee/6/api/javax/mail/Authenticator.html#getPasswordAuthentication%28%29
需要密码身份验证时调用。子类应该 重写默认实现,这将返回 null。
当提供程序需要知道用户名或密码时,它会回调 Authenticator 的 SMTPAuthenticator 子类中的 getPasswordAuthentication(( 方法。这将返回一个密码身份验证对象:
@Override
protected PasswordAuthentication getPasswordAuthentication(){....}