Search code examples
javajakarta-mailauthenticator

Is there a way to get username & password from javax.mail.Authenticator and how does it work?


So I am building a email client and to authenticate to the server i'm connecting to i've seen this been used alot:

Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

I can't say I have fully grasped how this piece of code works other than somewhere along the lines of it being used to login to the server.

Could someone take the time to explain how it works to me?

I have been trying to use the username value so I don't have to store it in my Properties file but I cannot instantiate it and I cannot find any get methods for it..

Any help is appreciated!


Solution

  • The best explanation is that you almost never need that code. It's left over from very, very, very old versions of JavaMail, and everyone just keeps copying and pasting that code because no one knows how to write code from scratch anymore.

    The longer explanation is that an Authenticator is just a way for JavaMail to ask the application for a username and password, which allows the application to ask the user for a username and application. In the simple case, there's no "asking" involved, everything is static, and the Authenticator is just a class that holds the username and password and returns them when called. That's what happens in the code above where an anonymous inner class that's a subclass of Authenticator defines a method that returns a PasswordAuthentication "struct" containing the username and password.