Is there a way to verify the user credentials of the SMTP server without sending email or connecting to POP / IMAP. Some of the code I tried to write fails. You can find what is missing there.
Do not worry about Email / Password. I know it there.
NOTE. If you are trying to execute code. Case 1 must be transmitted when providing the correct credentials. If this fails, someone changed the password. You must use a different email address.
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
public class EmailTest {
public static void main(String[] args) {
EmailHelper eh = new EmailHelper();
String name = "AAA";
String email = "mymasterpainter@gmail.com";
String smtpHost = "smtp.gmail.com";
String serverPort = "587";
String requireAuth = "true";
String dontuseAuth = "false";
String userName = email;
String password = "zaq12wsx";
String incorrectPassword = "someRandomPassword";
String enableSTARTTLS = "true";
String dontenableSTARTTLS = "false";
try {
eh.sendMail(name, email, smtpHost, serverPort, requireAuth,
userName, password, enableSTARTTLS);
System.out.println("Case 1 Passed");
eh.sendMail(name, email, smtpHost, serverPort, requireAuth,
userName, password, dontenableSTARTTLS);
System.out.println("Case 2 Passed");
eh.sendMail(name, email, smtpHost, serverPort, dontuseAuth, "", "",
dontenableSTARTTLS);
System.out.println("Case 3 Passed");
eh.sendMail(name, email, smtpHost, serverPort, requireAuth,
userName, incorrectPassword, dontenableSTARTTLS);
System.out.println("Case 4 Passed");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
class EmailHelper {
private Properties properties = null;
private Authenticator authenticator = null;
private Session session = null;
public void sendMail(String name, String email, String smtpHost,
String serverPort, String requireAuth, String userName,
String password, String enableSTARTTLS) throws MessagingException {
properties = System.getProperties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.smtp.port", serverPort);
properties.put("mail.smtp.starttls.enable", enableSTARTTLS);
properties.put("mail.smtp.auth", requireAuth);
properties.put("mail.smtp.timeout", 20000);
authenticator = new SMTPAuthenticator(userName, password);
session = Session.getInstance(properties, authenticator);
Transport tr = session.getTransport("smtp");
tr.connect();
}
}
class SMTPAuthenticator extends Authenticator {
private String userName = null;
private String password = null;
public SMTPAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}