Oct 12

When using an SMTP server that requires authentication with javamail we need a way to pass the username and password. Javamail provides an Authenticator class for this which we need to subclass to use.

For standard usage we just need to override the getPasswordAuthentication() method to return a PasswordAuthentication instance containing the username and password to be used by javamail when authenticating with the SMTP server.

	class PasswordAuthenticator extends javax.mail.Authenticator {
	    public PasswordAuthentication getPasswordAuthentication() {
			String user = "username@gmail.com";
			String pwd = "password";
			return new PasswordAuthentication(user, pwd);

Once we have our authenticator we pass it (along with standard properties) to create our javamail session.

	    Authenticator authenticator = new PasswordAuthenticator();
	    Session session = Session.getDefaultInstance(props, authenticator);

You can then use the session to send your mail.

written by objects \\ tags: , , ,