menu

Monday, November 10, 2014

Using Gmail Servers in JavaMail API

Introduction:

     In the previous post we mention about the basics of email protocols and show how to configure Apache James server to use in JavaMail API.Today we see how to use Gmail servers instead of using local Apache James server.The JavaMail API part is same but we have to configure the properties of the email session according to Gmail servers in addition to obtaining an application password from the gmail.

Obtain Application Password:

     First of all, we have to get an application password to use in our JavaMail API. When we try to use our gmail password an error occurred indicating "Username and password are not accepted" giving the following link.
http://support.google.com/accounts/bin/answer.py?answer=185833
This link says that you have to create an application password instead of using the gmail password for security reasons. Follow the steps shown in the link and create your application password.

Sending Mail Using Gmail SMTP Server:

      The following java code can be use to send an email using Gmail SMTP server.If you want to use SSL enabled you have to comment out  line 3 and 4 while commenting the line 1 and 2.As you can understand while the SMTP port of Gmail is 587 when you enable SSL it is 465.If you are not using SSL you have to set true to attribute "mail.smtp.starttls.enable". You don't have to set the FROM attribute as the user you provided in authentication will be automatically used as the FROM attribute.

package tr.com.aligelenler;

import java.text.SimpleDateFormat;

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

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailUseGmail {

private static final String USER = "your_email@gmail.com";
private static final String PASSWORD = "your_app_password";

public static void main(String[] args) {
try {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.host", "smtp.gmail.com");

1 props.put("mail.smtp.port", "587");
2 props.put("mail.smtp.starttls.enable", "true");

3 //props.put("mail.smtp.socketFactory.port", "465");
4 //props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USER, PASSWORD);
}
});
MimeMessage msg = new MimeMessage(session);
// msg.setFrom(new InternetAddress(USER)); No need to specify FROM attribute
msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse("sendmail1@gmail.com, sendmail2@gmail.com"));
msg.setSubject("You have a new mail");
msg.setText("This is a test message send at " + new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSSZ").format(new Date()));
Transport.send(msg);
} catch (MessagingException e) {
System.out.println(e.getMessage());
}
}

}

Reading Mail Using Gmail POP3 or IMAP Server:

     You can use the following java code to read your gmail inbox folder.The code that delete your mails is not working here, that's because i think a restriction of gmail server to prevent accidentally deleting emails. Here I use imap as the mail fetch protocol.If you want to use pop3 protocol you have to change the properties as below. Using SSL is mandatory when reading your emails.

props.put("mail.store.protocol", "pop3");
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.socketFactory.port", "995");
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

package tr.com.aligelenler;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;

public class ReadMailUseGmail {

private static final String USER = "your_email@gmail.com";
private static final String PASSWORD = "your_app_password";
private static final boolean CLEAR = false;

public static void main(String[] args) {
Store store = null;
Folder inbox = null;
try {
Properties props = new Properties();
props.put("mail.store.protocol", "imap");
props.put("mail.imap.host", "imap.gmail.com");
props.put("mail.imap.socketFactory.port", "993");
props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.debug", "true");

Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USER, PASSWORD);
}
});
store = session.getStore();
store.connect();
Folder root = store.getDefaultFolder();
inbox = root.getFolder("inbox");
inbox.open(Folder.READ_WRITE);
Message[] mails = inbox.getMessages();
if (mails.length == 0) {
System.out.println("There are no messages");
}
for (int i = 0; i < 10; i++) {
MimeMessage mail = (MimeMessage) mails[i];
System.out.println("From: " + mail.getFrom()[0]);
System.out.println("To: " + mail.getRecipients(Message.RecipientType.TO)[0]);
System.out.println("Subject: " + mail.getSubject());
System.out.println("Content: " + mail.getContent());
if (CLEAR) {
mail.setFlag(Flags.Flag.DELETED, true);
}
}
} catch (MessagingException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (inbox != null && inbox.isOpen())
inbox.close(true);
if (store != null)
store.close();
} catch (MessagingException e) {
System.out.println(e.getMessage());
}
}
}
}

Conclusion:

    Today I showed how to use simple JavaMail API using Gmail servers to send and read emails.The only trick is to obtain a application password to use in the authentication of Gmail server.

You can download the source code from here.

No comments:

Post a Comment