IMAP presents mail messages as entries in a hierarchy of folders, one of which will be an inbox.
Java Mail comes with Provider implementations for POP3 and IMAP, and the secure versions of those as POP3S and IMAPS.
This HowTo connects to a Google Mail account with IMAPS. IMAP protocol is more advanced than POP. With IMAP, you can talk back to the server and sync your changes automatically.
This Howto connects to a server using the IMAPS (Secure, encrypted IMAP) to download messages with or without attachments and save them into files.
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class ReceiveMailImap {
public ReceiveMailImap() {}
//
// inspired by :
// http://www.mikedesjardins.net/content/2008/03/using-javamail-to-read-and-extract/
//
public static void doit() throws MessagingException, IOException {
Folder folder = null;
Store store = null;
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
// session.setDebug(true);
store = session.getStore("imaps");
store.connect("imap.gmail.com","myemail@gmail.com", "******");
folder = store.getFolder("Inbox");
/* Others GMail folders :
* [Gmail]/All Mail This folder contains all of your Gmail messages.
* [Gmail]/Drafts Your drafts.
* [Gmail]/Sent Mail Messages you sent to other people.
* [Gmail]/Spam Messages marked as spam.
* [Gmail]/Starred Starred messages.
* [Gmail]/Trash Messages deleted from Gmail.
*/
folder.open(Folder.READ_WRITE);
Message messages[] = folder.getMessages();
System.out.println("No of Messages : " + folder.getMessageCount());
System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
for (int i=0; i < messages.length; ++i) {
System.out.println("MESSAGE #" + (i + 1) + ":");
Message msg = messages[i];
/*
if we don''t want to fetch messages already processed
if (!msg.isSet(Flags.Flag.SEEN)) {
String from = "unknown";
...
}
*/
String from = "unknown";
if (msg.getReplyTo().length >= 1) {
from = msg.getReplyTo()[0].toString();
}
else if (msg.getFrom().length >= 1) {
from = msg.getFrom()[0].toString();
}
String subject = msg.getSubject();
System.out.println("Saving ... " + subject +" " + from);
// you may want to replace the spaces with "_"
// the TEMP directory is used to store the files
String filename = "c:/temp/" + subject;
saveParts(msg.getContent(), filename);
msg.setFlag(Flags.Flag.SEEN,true);
// to delete the message
// msg.setFlag(Flags.Flag.DELETED, true);
}
}
finally {
if (folder != null) { folder.close(true); }
if (store != null) { store.close(); }
}
}
public static void saveParts(Object content, String filename)
throws IOException, MessagingException
{
OutputStream out = null;
InputStream in = null;
try {
if (content instanceof Multipart) {
Multipart multi = ((Multipart)content);
int parts = multi.getCount();
for (int j=0; j < parts; ++j) {
MimeBodyPart part = (MimeBodyPart)multi.getBodyPart(j);
if (part.getContent() instanceof Multipart) {
// part-within-a-part, do some recursion...
saveParts(part.getContent(), filename);
}
else {
String extension = "";
if (part.isMimeType("text/html")) {
extension = "html";
}
else {
if (part.isMimeType("text/plain")) {
extension = "txt";
}
else {
// Try to get the name of the attachment
extension = part.getDataHandler().getName();
}
filename = filename + "." + extension;
System.out.println("... " + filename);
out = new FileOutputStream(new File(filename));
in = part.getInputStream();
int k;
while ((k = in.read()) != -1) {
out.write(k);
}
}
}
}
}
}
finally {
if (in != null) { in.close(); }
if (out != null) { out.flush(); out.close(); }
}
}
public static void main(String args[]) throws Exception {
ReceiveMailImap.doit();
}
}
Done! Happy Coding!
Related posts:
Number Formatting in Java
Java Program to Implement Triply Linked List
Spring Security OAuth2 – Simple Token Revocation
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Implement Heap Sort Using Library Functions
How to Get the Last Element of a Stream in Java?
Java Program to Implement Solovay Strassen Primality Test Algorithm
Java Program to Optimize Wire Length in Electrical Circuit
Java Program to implement Sparse Vector
Spring Boot - Securing Web Applications
Converting between an Array and a List in Java
Guide to PriorityBlockingQueue in Java
Using JWT with Spring Security OAuth
Java Program to Check if a Point d lies Inside or Outside a Circle Defined by Points a, b, c in a Pl...
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Java Program to Implement the String Search Algorithm for Short Text Sizes
Guide to System.gc()
Java Program to Implement Levenshtein Distance Computing Algorithm
Jackson JSON Views
Assertions in JUnit 4 and JUnit 5
Spring Security Basic Authentication
Java Program to Implement Bubble Sort
Server-Sent Events in Spring
Kết hợp Java Reflection và Java Annotations
Java Program to Implement Double Ended Queue
Build a REST API with Spring and Java Config
DynamoDB in a Spring Boot Application Using Spring Data
Java Program to Check if it is a Sparse Matrix
Object cloning trong java
Chương trình Java đầu tiên
Guide to Apache Commons CircularFifoQueue
Java Program to Implement Dijkstra’s Algorithm using Priority Queue