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.

13 comments:

  1. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. Twitter Website Scraper Software

    ReplyDelete
  2. Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks Web Scraping FAQ

    ReplyDelete
  3. Personally I think overjoyed I discovered the blogs. water filter for home

    ReplyDelete
  4. New web site is looking good. Thanks for the great effort. email and text extractor from cell phone

    ReplyDelete
  5. I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. mail merge bulk email

    ReplyDelete
  6. I was able to try their new online course as well. It is indeed very convenient and their lessons about brand naming were very insightful! Definitely worth every penny. CBT Email Extractor

    ReplyDelete
  7. Manage Engine Service Desk Plus is a Web-based, simple to utilize HelpDesk programming with Asset Management whose highlights incorporate agreement the executives, programming permit the board, network stock administration, buying, dynamic index and LDAP combinations and information the board functionalities. help desk softwares

    ReplyDelete
  8. A rootkit furnishes the interloper with authoritative advantages, the most significant level of consent that a client can have. The overseer includes all out opportunity inside the PC framework, which implies that the person in question can introduce and uninstall programs, erase records, and change arrangement settings, among different exercises.elf file format

    ReplyDelete
  9. Find the best essays on is my friend's profile page. Email Harvester

    ReplyDelete
  10. Innovation (from Greek τî­χνη, techne, "craftsmanship, ability, tricky of hand"; and - λογî¯α, - logia[1]) is the making, alteration, use, and information on apparatuses, Bitrss best cryptocurrency investment

    ReplyDelete
  11. They're furthermore several techniques have been you may get school funding to your home based business.
    US Business Funding

    ReplyDelete
  12. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. buy rust steam accounts

    ReplyDelete
  13. I high appreciate this post. It’s hard to find the good from the bad sometimes, but I think you’ve nailed it! would you mind updating your blog with more information? ufabet เว็บตรง

    ReplyDelete