Working with Mailboxes Using the IMAP Service Client in Java
ImapClient from the com.aspose.email.services.inetmail.client package reads and manages messages on an IMAP server. It requires a mail protocol library on the classpath. For details, see Mail Protocol Libraries Setup.
com.aspose.email package has a class with the same name, which is described in Working with IMAP Client. Use explicit imports to select the class you need.
Connecting to a Server
The following code sample creates a client and lists the names of the folders in a mailbox. Other code samples on this page use the imap variable created here.
import com.aspose.email.services.inetmail.auth.PasswordCredentials;
import com.aspose.email.services.inetmail.client.ImapClient;
import com.aspose.email.services.inetmail.model.ImapFolder;
try (ImapClient imap = ImapClient.builder()
.host("imap.example.com")
.port(993)
.ssl()
.credentials(new PasswordCredentials("user@example.com", "password"))
.build()) {
for (ImapFolder folder : imap.listFolders()) {
System.out.println(folder.getFullName() + ": " + folder.getMessageCount()
+ " messages, " + folder.getUnreadCount() + " unread");
}
}
The client connects when it performs its first operation, not when you call build. It keeps the connection until you close the client.
Listing Messages
To list the messages in a folder, call folder with the full name of the folder, and then call list. The method returns a list of InetMessageInfo objects, which contain the main properties of each message without its body:
import com.aspose.email.services.inetmail.model.InetMessageInfo;
for (InetMessageInfo info : imap.folder("INBOX").list()) {
System.out.println(info.getUid() + ": " + info.getSubject() + ", from " + info.getFrom());
}
Use the value returned by getUid to access the message in the following sections.
Searching for Messages
To return only the messages that match a set of conditions, pass an ImapSearchQuery object to list. A message must match all the conditions that you set.
| Builder method | Condition |
|---|---|
unseen() |
The message is not marked as seen |
from(String) |
The sender contains the text |
subject(String) |
The subject contains the text |
bodyContains(String) |
The message body contains the text |
since(Date) |
The message was sent on or after the date |
before(Date) |
The message was sent before the date |
The following code sample finds unseen messages from a sender:
import com.aspose.email.services.inetmail.model.ImapSearchQuery;
import com.aspose.email.services.inetmail.model.InetMessageInfo;
import java.util.List;
ImapSearchQuery query = ImapSearchQuery.builder()
.unseen()
.from("user@example.com")
.build();
List<InetMessageInfo> messages = imap.folder("INBOX").list(query);
System.out.println(messages.size());
Reading a Message
To get a complete message with its body and attachments, call fetch. The following code sample prints the message and saves its attachments to files:
import com.aspose.email.services.inetmail.model.InetAttachment;
import com.aspose.email.services.inetmail.model.InetMessage;
import java.nio.file.Files;
import java.nio.file.Paths;
InetMessage message = imap.folder("INBOX").message(uid).fetch();
System.out.println(message.getSubject());
System.out.println(message.getSentDateAsDate());
System.out.println(message.getTextBody());
System.out.println(message.getHtmlBody());
for (InetAttachment attachment : message.getAttachments()) {
System.out.println(attachment.getName() + ": " + attachment.getContentType());
Files.write(Paths.get(attachment.getName()).getFileName(), attachment.getData());
}
getSentDateAsDate returns the sent date as java.util.Date, and InetMessageInfo has the same method. getSentDate returns this date as text in the Date.toString format, which depends on the time zone of the computer. getContentType of an attachment returns only the media type in lowercase, for example text/plain, without parameters such as charset.
Changing Message Flags
Use markSeen and markFlagged to set or clear the flags of a message:
imap.folder("INBOX").message(uid).markSeen(true);
imap.folder("INBOX").message(uid).markFlagged(true);
Moving a Message
To move a message to another folder, call moveTo with the full name of the target folder. The target folder must already exist, because ImapClient cannot create folders.
imap.folder("INBOX").message(uid).moveTo("Archive");
Deleting a Message
To delete a message from the server, call delete:
imap.folder("INBOX").message(uid).delete();
Handling Errors
When an operation fails, for example because of a wrong password or a folder that does not exist, the client throws MailClientException, which extends java.io.IOException:
import com.aspose.email.services.inetmail.MailClientException;
try {
System.out.println(imap.folder("NoSuchFolder").list().size());
} catch (MailClientException e) {
System.out.println(e.getMessage() + ": " + e.getCause().getMessage());
}