Java code example for downloading emails using IMAP

更新时间:
复制 MD 格式

This topic provides a Java code example for downloading emails using 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) {
        // Mail server configuration
        String host = "imap.qiye.aliyun.com"; // Set host to imap.qiye.aliyun.com or imap.mxhichina.com
        String username = "";
        String password = "";
        // Connection property configuration
        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 SSLHandshakeException error, uncomment this line and retry.

        // The path to the local folder. Replace this with your actual folder path.
        String folderPath = "D:\\Folder1\\Folder1-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);
            // Get the list of emails
            Message[] messages = inbox.getMessages();
            // Traverse the emails and download them in EML format
            for (Message message : messages) {
                String subject = message.getSubject();
                String fileName = subject + ".eml";
                // Build the local file path
                String filePath = folderPath + File.separator + fileName;
                // Download the email to the local folder
                FileOutputStream fos = new FileOutputStream(filePath);
                message.writeTo(fos);
                System.out.println("Downloading email: " + fileName);
            }
            // Close the connection
            inbox.close(false);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}