EJB(xml/mail/jms/jdbc)
2018.04.02 / 02:40

Receive e-mail messages from a POP3-IMAP server

ÀλçÀ̵åÀÚ¹Ù
Ãßõ ¼ö 241

This article walks through steps to download e-mail messages from a POP3/IMAP server¡¯s inbox, using JavaMail API. The following picture depicts how messages are logically stored on the server:

mail store

we can see, for each user account, the server has a store which is the storage of user¡¯s messages. The store is divided into folders, and the ¡°inbox¡± folder is the primarily folder which contains e-mail messages. A folder can contain both messages and sub-folders.

Speaking of JavaMail API¡®s language, it provides three corresponding classes: StoreFolder and Message.

-          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.

-          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 Folderclass 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.

-          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.

Typically, the steps to connect to a server and download new e-mail messages are as follows:

-          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.

 

Recommended Book: JavaMail API

 

And following is code of a sample program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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);
    }
}