Search code examples
javaemailjakarta-mail

Cannot access parent's protected method in Java


I have this problem:

A java class that contains an inner class. The inner class (Authenticator) extends the javax.mail.Authenticator (note the same name for both class and subclass).

The problem is that I can't access the protected method getPasswordAuthentication unless the inner class has the same name as the extended class (I mean Authenticator extends javax.mail.Authenticator). If I write private class SMTPAuthenticator extends javax.mail.Authenticator then I can't access anymore the protected getPasswordAuthentication. See code below:

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailWithPasswordAuthentication {
    public static void main(String[] args) throws MessagingException {
        new MailWithPasswordAuthentication().run();
    }

    private void run() throws MessagingException {
        Message message = new MimeMessage(getSession());

        message.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
        message.addFrom(new InternetAddress[] { new InternetAddress("[email protected]") });

        message.setSubject("the subject");
        message.setContent("the body", "text/plain");

        Transport.send(message);
    }

    private Session getSession() {
        Authenticator authenticator = new Authenticator();

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.setProperty("mail.smtp.auth", "true");

        properties.setProperty("mail.smtp.host", "mail.example.com");
        properties.setProperty("mail.smtp.port", "25");

        return Session.getInstance(properties, authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator {
        private PasswordAuthentication authentication;

        public Authenticator() {
            String username = "auth-user";
            String password = "auth-password";
            authentication = new PasswordAuthentication(username, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }
}

thankx, A


Solution

  • If you rename your Authenticator class to SMTPAuthenticator, you should also change the line:

    Authenticator authenticator = new Authenticator();
    

    to

    SMTPAuthenticator authenticator = new SMTPAuthenticator();
    

    The reason you get the error is that only the SMTPAuthenticator class contains the getPasswordAuthentication() method, not the base Authenticator class