Thursday, June 9, 2011

How to set up an email smtp client to work with

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.


String host = "";
  int port = 587;
  String username = "your_gmail_login";
  String password = "your_password";
  String from = "";

  Properties props = new Properties();
  props.put("mail.smtp.starttls.enable", "true");
  props.put("", 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
   message.setSubject("Hey there dude!");
      ("Here's the body of my email, blah blah blah");
   Transport transport = session.getTransport("smtp");
   transport.connect(host, port, username, password);

And this class too...

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

No comments:

Post a Comment