package com.storlead.mail.connection.client;

import com.storlead.mail.connection.MailConnection;
import com.storlead.mail.connection.MailConnectionFactory;

import javax.mail.*;
import java.util.Arrays;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-05-30 16:31
 */

public class MailReceiverUtil {
    public static void receiveInboxEmails(String protocol, String host, String port, String user, String password) {
        receiveEmails(protocol, host, port, user, password, "INBOX");
    }

    public static void receiveSentEmails(String protocol, String host, String port, String user, String password) {
        receiveEmails(protocol, host, port, user, password, "Sent");
    }

    private static void receiveEmails(String protocol, String host, String port, String user, String password, String folderName) {
        MailConnectionFactory connectionFactory = MailConnectionFactory.getFactory(protocol, host, port, user, password);
        MailConnection mailConnection = connectionFactory.createConnection();
        try {
            mailConnection.connect();
            Store store = mailConnection.getStore();
            Folder folder = store.getFolder(folderName);
            folder.open(Folder.READ_WRITE);
            Message[] messages = folder.getMessages();
            for (Message message : messages) {
                System.out.println(protocol.toUpperCase() + " - Subject: " + message.getSubject());
                System.out.println(protocol.toUpperCase() + " - From: " + Arrays.toString(message.getFrom()));
                System.out.println("------------------------------------------------");
            }

            folder.close(false);
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            mailConnection.close();
        }
    }
}

