Sunday, January 21, 2007

SMTP Setting for Gmail in javamail

SMTP server of the Gmail needs Authenticator object instead of plain username and password.
It took me about 2 hours to figure out .....

String smtpHost = "";
String smtpPort = "465";
String from = "";
String to = "";
final String username = "xxxxxxxx";
final String password = "xxxxxxx";

// Get system properties
Properties props = System.getProperties();
props.setProperty("", smtpHost);
props.setProperty("mail.smtp.socketFactory.class", "");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
props.setProperty("mail.smtp.auth", "true");

// Get session
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Hello JavaMail");
message.setText("Welcome to JavaMail");

// Send message

No comments: