How to receive emails from server using JavaMail
- Details
- Written by Nam Ha Minh
- Last Updated on 09 July 2019   |   Print Email
- A Store object can be obtained from the current session by invoking the method getStore(String protocol) of Session class. Connecting to the Store by calling its method connect(String user, String pass), disconnecting by calling its close() method.
- A Folder object can be obtained from the store by invoking the getFolder(String folderName) method. For a regular mail box, the folder name must be “inbox” (case-insensitive). The most important methods of the Folder class are:
- open(int mode): Opens the folder either in READ_ONLY mode or READ_WRITE mode.
- getMessages(): Retrieves an array of Message objects which are marked un-read in the folder. A Message object may be a lightweight reference, and its detailed content will be filled up on demand.
- close(boolean expunge): Closes the folder, and permanently remove all messages which are marked delete, if expunge is true.
- A Message object represents an e-mail message. To get detailed attributes of a message, the following methods can be called on the Message object:
- Address[] getFrom(): returns a list of senders in From attribute of the message.
- Address[] getRecipients(Message.RecipientType type): gets recipient addresses of the message, type can be either TO or CC.
- String getSubject(): gets subject of the message.
- Date getSentDate(): gets date and time when the message was sent.
- Object getContent(): gets content of the message.
- Prepare a Properties object which holds server settings such as host, port, protocol…
- Create a session to initiate a working session with the server.
- Obtain a store from the session by a specific protocol (IMAP or POP3). IMAP is recommended.
- Connect to the store using a credential (username and password).
- Gets inbox folder from the store.
- Open the inbox folder.
- Retrieve messages from the folder.
- Fetch details for each message.
- Close the folder.
- Close the store.
And following is code of a sample program:package net.codejava.mail; import java.util.Properties; import javax.mail.Address; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; /** * This program demonstrates how to get e-mail messages from a POP3/IMAP server * * @author www.codejava.net * */ public class EmailReceiver { /** * Returns a Properties object which is configured for a POP3/IMAP server * * @param protocol either "imap" or "pop3" * @param host * @param port * @return a Properties object */ private Properties getServerProperties(String protocol, String host, String port) { Properties properties = new Properties(); // server setting properties.put(String.format("mail.%s.host", protocol), host); properties.put(String.format("mail.%s.port", protocol), port); // SSL setting properties.setProperty( String.format("mail.%s.socketFactory.class", protocol), "javax.net.ssl.SSLSocketFactory"); properties.setProperty( String.format("mail.%s.socketFactory.fallback", protocol), "false"); properties.setProperty( String.format("mail.%s.socketFactory.port", protocol), String.valueOf(port)); return properties; } /** * Downloads new messages and fetches details for each message. * @param protocol * @param host * @param port * @param userName * @param password */ public void downloadEmails(String protocol, String host, String port, String userName, String password) { Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); try { // connects to the message store Store store = session.getStore(protocol); store.connect(userName, password); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; Address[] fromAddress = msg.getFrom(); String from = fromAddress[0].toString(); String subject = msg.getSubject(); String toList = parseAddresses(msg .getRecipients(RecipientType.TO)); String ccList = parseAddresses(msg .getRecipients(RecipientType.CC)); String sentDate = msg.getSentDate().toString(); String contentType = msg.getContentType(); String messageContent = ""; if (contentType.contains("text/plain") || contentType.contains("text/html")) { try { Object content = msg.getContent(); if (content != null) { messageContent = content.toString(); } } catch (Exception ex) { messageContent = "[Error downloading content]"; ex.printStackTrace(); } } // print out details of each message System.out.println("Message #" + (i + 1) + ":"); System.out.println("\t From: " + from); System.out.println("\t To: " + toList); System.out.println("\t CC: " + ccList); System.out.println("\t Subject: " + subject); System.out.println("\t Sent Date: " + sentDate); System.out.println("\t Message: " + messageContent); } // disconnect folderInbox.close(false); store.close(); } catch (NoSuchProviderException ex) { System.out.println("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { System.out.println("Could not connect to the message store"); ex.printStackTrace(); } } /** * Returns a list of addresses in String format separated by comma * * @param address an array of Address objects * @return a string represents a list of addresses */ private String parseAddresses(Address[] address) { String listAddress = ""; if (address != null) { for (int i = 0; i < address.length; i++) { listAddress += address[i].toString() + ", "; } } if (listAddress.length() > 1) { listAddress = listAddress.substring(0, listAddress.length() - 2); } return listAddress; } /** * Test downloading e-mail messages */ public static void main(String[] args) { // for POP3 //String protocol = "pop3"; //String host = "pop.gmail.com"; //String port = "995"; // for IMAP String protocol = "imap"; String host = "imap.gmail.com"; String port = "993"; String userName = "your_email_address"; String password = "your_email_password"; EmailReceiver receiver = new EmailReceiver(); receiver.downloadEmails(protocol, host, port, userName, password); } }In the EmailReceiver class above, the primary method is downloadEmail(), and the two helper methods, getServerProperties() and parseAddresses(). The server information used for testing is Gmail’s IMAP server, and remember to change userName and password to match your account.
NOTES:
You need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>
Other JavaMail Tutorials:
- How to send plain text email using JavaMail
- How to send email in HTML format using JavaMail
- How to send email with attachments using JavaMail
- How to insert images into email for sending with JavaMail
- How to search email messages using JavaMail
- How to delete emails programmatically using JavaMail
- How to download attachments in emails using JavaMail
Comments
javax.mail.Provider: com.sun.mail.imap.IMAPProvider not a subtype
Any idea about the reason for this error?
For sending emails in Spring Boot, kindly follow this tutorial: www.codejava.net/.../email-sending-tutorial