This article provides the Java call example of email download by IMAP.
import java.io.FileOutputStream;
import java.io.File;
import java.util.Properties;
import javax.mail.*;
public class ImapEmailDownloader {
public static void main(String[] args) {
// Configure the email server.
String host = "";
String username = "";
String password = "";
// Configure the connection properties.
Properties properties = new Properties();
properties.put("mail.store.protocol", "imap");
properties.put("mail.imap.host", host);
properties.put("mail.imap.port", "993");
properties.put("mail.imap.ssl.enable", "true");
//properties.put("mail.imap.ssl.protocols", "TLSv1.2"); //If you encounter an error SSLHandShakeException, please try this option
// The local folder path. Please replace it with the actual folder path.
String folderPath = "D :\\ Folder 1\\Folder 1-1";
try {
// Create a session object.
Session session = Session.getDefaultInstance(properties);
// Connect to the mail server.
Store store = session.getStore();
store.connect(username, password);
// Open the inbox.
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
// Obtain the email list.
Message[] messages = inbox.getMessages();
// Traverse emails and download emails in the EML format.
for (Message message : messages) {
String subject = message.getSubject();
String fileName = subject + ".eml";
// Build the path of the local file.
String filePath = folderPath + File.separator + fileName;
// Download the email to the local folder.
FileOutputStream fos = new FileOutputStream(filePath);
message.writeTo(fos);
System.out.println("Download email:" + fileName);
}
// Close the connection.
inbox.close(false);
store.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}