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]

No comments: