IMAP下载邮件之Java调用示例

本文为IMAP下载邮件Java代码调用示例。

import java.io.FileOutputStream;
import java.io.File;
import java.util.Properties;
import javax.mail.*;

public class ImapEmailDownloader {
    public static void main(String[] args) {
        // 邮件服务器配置
        String host = "imap.qiye.aliyun.com"; //host填写imap.qiye.aliyun.com或imap.mxhichina.com
        String username = "";
        String password = "";
        // 连接属性配置
        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"); //如遇到报错SSLHandshakeException可去掉注释后重试

        //本地文件夹路径,请换成实际的文件夹路径。
        String folderPath = "D:\\文件夹1\\文件夹1-1";

        try {
            // 创建会话对象
            Session session = Session.getDefaultInstance(properties);
            // 连接到邮件服务器
            Store store = session.getStore();
            store.connect(username, password);
            // 打开收件箱
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            // 获取邮件列表
            Message[] messages = inbox.getMessages();
            // 遍历邮件并下载EML格式的邮件
            for (Message message : messages) {
                String subject = message.getSubject();
                String fileName = subject + ".eml";
                //构建本地文件路径
                String filePath = folderPath + File.separator + fileName;
                //下载邮件到本地文件夹
                FileOutputStream fos = new FileOutputStream(filePath);
                message.writeTo(fos);
                System.out.println("下载邮件:" + fileName);
            }
            // 关闭连接
            inbox.close(false);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}