Jul 12, 2008

Force authentication with Java Mail API

package com;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.MimeMessageHelper;

public class EmailTest {

/**
* @param args
*/
public static void main(String[] args) {
try {
String[] strarr = { "recipient@email.addresses" };
postMail(strarr, "Test u", "Test Mesage", "from@email.address", false);
System.out.println("Mail sent!...");
} catch (MessagingException e) {
e.printStackTrace();
}

}
public static void postMail(String recipients[], String subject, String message, String from, boolean isHtml) throws MessagingException {
boolean debug = false;

// Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host","hostipaddr");
String hostEmail = "admin@mail.com";
String pwd = "password";
// create some properties and get the default Session
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props, new ForcedAuthenticator(hostEmail,pwd));
session.setDebug(debug);

// create a message
MimeMessage msg = new MimeMessage(session);

MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(msg);

mimeMessageHelper.setTo(recipients);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setReplyTo(from);
mimeMessageHelper.setText(message, isHtml);

Transport.send(mimeMessageHelper.getMimeMessage());
}
}
class ForcedAuthenticator extends Authenticator {
String username;
String password;
public ForcedAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.username, this.password);
}
}