Tuesday, October 2, 2012

Send Mail Via Gmail

I already spent some time few years ago to figure that out and now I spent this time again.
So here's the short code snippet with an example how to send mail using Java Mail and GMail.

First, pom.xml. Include the following dependencies:

<dependency>
    <groupid>javax.mail</groupId>
    <artifactid>javax.mail-api</artifactId>
    <version>1.4.5</version>
</dependency>
<dependency>
    <groupid>javax.mail</groupId>
    <artifactid>mail</artifactId>
    <version>1.4.5</version>
</dependency>

And now the code:

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.smtp.SMTPTransport;

public class SendMail {

 public static void main(String[] args) throws Exception {
  Properties props = System.getProperties();
  props.put("mail.smtps.host", "smtp.gmail.com");
  props.put("mail.smtps.auth", "true");
  Session session = Session.getInstance(props, null);
  Message msg = new MimeMessage(session);
  msg.setFrom(new InternetAddress("somebody@gmail.com"));
  msg.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse("somebody_else@gmail.com", false));
  msg.setSubject("I'm the subject!");
  msg.setText("And I'm text of your message");
  msg.setHeader("X-Mailer", "Java Program");
  msg.setSentDate(new Date());
  SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
  t.connect("smtp.gmail.com", "somebody@gmail.com",
    "here comes the password");
  t.sendMessage(msg, msg.getAllRecipients());
  System.out.println("Response: " + t.getLastServerResponse());
  t.close();
 }
}

And the thanks goes here.