I'm trying to write a simple Java program that just sends emails and retrieves text from emails in my inbox, and I'm a little confused about how the Authenticator object works. Why is there bracketed code immediately after the constructor and how does it function? I found this example code for creating a Session object, and it works fine, but I've never seen this kind of notation before and can't find any other examples of it elsewhere.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
From the The Java™ Tutorials - Anonymous Classes:
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
From the JAVAMAIL API FAQ:
A more straightforward approach is to call the connect method that takes a username and password when connecting to a Store. When sending a message, use the static Transport.send method that takes a username and password.