Introduction
This article explains how to receive emails using the JavaMail API and a basic example.
About JavaMail API
All of the basics about JavaMail API can be read from my previous article, in which all of the concepts, definitions, packages, and classes have been explained in detail. They are available at the following link:
The following explains how to receive mail using the JavaMail API.
When receiving mail, we need to use all of the core classes of packages used, such as javax.mail, javax.mail.internet, javax.mail.activation, java.io, and so on.
When we receive mail, we sometimes receive attachments with the mail. That is done using the multipart and BodyPart classes.
Also, when receiving mail, we need to load the following two jar files:
Without these jar files, your packages (javax.mail and javax.mail.internet) will not work and the mail will not be received. Both of the jar files have been attached to the previous article, where you can download those files. You can also download the files from the Oracle website.
Now, concentrate on the following example of receiving mail, using the JavaMail API.
Example of receiving mail
Here we created a few classes that are different from those used in the example of sending mail. So, read and analyse the differences between the two.
- import javax.mail.*;
- import javax.activation.*;
- import javax.mail.internet.*;
- import java.util.*;
- import java.io.*;
- class ReadAttachment {
- public static void main(String agrs[]) throws Exception {
- String host = "mail.c-sharpcorner.com";
- final String user = "[email protected]";
- final String password = "xxxxxxx";
- Properties properties = System.getProperties();
- properties.setProperty("mail.smtp.host", host);
- properties.put("mail.smtp.auth", "true");
- Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
- protected PasswordAuthentication getPassworAuthentication() {
- return new PasswordAuthentication(user, password);
- }
- });
- Store store = session.getStore("pop3");
- store.connect(host, user, password);
- Folder folder = store.getFolder("inbox");
- folder.open(Folder.READ_WRITE);
- Message[] message = folder.getMessages();
- for (int i = 0; i < message.length; i++) {
- System.out.println("-------" + (i + 1) + "-------");
- System.out.println(message[i].getSentDate());
- Multipart multipart = (Multipart) message[i].getContent();
- for (int j = 0; j < multipart.getCount(); j++) {
- BodyPart bodyPart = multipart.getBodyPart(i);
- InputStream stream = bodyPart.getInputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(stream));
- while (br.ready()) {
- System.out.println(br.readLine());
- }
- System.out.println();
- }
- System.out.println();
- }
- folder.close(true);
- store.close();
- }
- }
This will help to receive emails with an attachment.