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

1 comment:

Tim Archer said...

I also have a few writeups on using Javamail.

I wrote one class to help me easily send emails from my Java applications using JavaMail. It supports relaying through SMTP servers that require authentication and has convenience methods for easily adding file attachments.

Check it out at:

And my other writeup is on using JavaMail to retrieve messages through POP3: