Thursday, June 9, 2011

How to set up an email smtp client to work with smtp.gmail.com

There's a bunch of implementations out there that don't work (possibly outdated or just plain broken. So, that's why I'm publishing this today--so I have a handy reference when I need it again.

Anyways, this one DOES work using gmail as the smtp agent.

Enjoy.


String host = "smtp.gmail.com";
  int port = 587;
  String username = "your_gmail_login";
  String password = "your_password";
  String from = "support@belisarius2000.com";

  Properties props = new Properties();
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.user", username);
  props.put("mail.smtp.password", password);
  props.put("mail.smtp.port", "587");
  props.put("mail.smtp.auth", "true");


   Session session = Session.getInstance(props,new 
     GMailAuthenticator(username, password));

   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress
      ("support@belisarius2000.com"));
   message.setRecipients(Message.RecipientType.TO,
      InternetAddress.parse(email));
   message.setSubject("Hey there dude!");
   message.setText
      ("Here's the body of my email, blah blah blah");
 
   Transport transport = session.getTransport("smtp");
   transport.connect(host, port, username, password);
 
   Transport.send(message);


And this class too...

class GMailAuthenticator extends Authenticator {
  String user;
  String pw;
  public GMailAuthenticator (String username, String password)
  {
    super();
    this.user = username;
    this.pw = password;
  }
  public PasswordAuthentication getPasswordAuthentication()
  {
    return new PasswordAuthentication(user, pw);
  }
}

No comments:

Post a Comment