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 .....

[code]
String smtpHost = "smtp.gmail.com";
String smtpPort = "465";
String from = "registeredGmailAccount@xxxxx.com";
String to = "xxxxxxxx@xxxxxxx.com";
final String username = "xxxxxxxx";
final String password = "xxxxxxx";

// Get system properties
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", smtpHost);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
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
Transport.send(message);
[/code]

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:
http://timarcher.com/?q=node/53

And my other writeup is on using JavaMail to retrieve messages through POP3:
http://timarcher.com/?q=node/52