Search code examples
javagmailjakarta-mail

Java mail. How to check if login was successful?


I have this class, that handles login to gmail. Program returns session no matter what email and password I enter. I don't understend how to check if login is successful before returning session object.

package mailActions;

import java.util.Properties;
import javax.mail.*;

public class Login {

    static Properties props = new Properties();

    public static Session login(final String username, final String password) {
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

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

        return session;
    }
}

Solution

  • The Session object just represents the configuration information you're using with JavaMail. You actually need to connect to a server to find out if you have the correct credentials. Use the Store.connect or Transport.connect methods, depending on what you're trying to do.