کار با پیام‌ها از سرور IMAP

فهرست‌برداری شناسه‌های پیام MIME از سرور

ImapMessageInfo MIME را فراهم می‌کند MessageId برای شناسایی پیام بدون استخراج کامل پیام. کد زیر نشان می‌دهد چگونه شناسهٔ پیام MIME را لیست کنیم.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
ImapClient client = new ImapClient();
client.setHost("domain.com");
client.setUsername("username");
client.setPassword("password");

try {
    ImapMessageInfoCollection messageInfoCol = client.listMessages("Inbox");
    for (ImapMessageInfo info : messageInfoCol) {
        // Display MIME Message ID
        System.out.println("Message Id = " + info.getMessageId());
    }
} catch (java.lang.RuntimeException ex) {
    System.out.println(ex.getMessage());
}

لیست کردن پیام‌ها از سرور

Aspose.Email یک نسخهٔ overload شدهٔ ۲ عضوی از listMessages() برای بازیابی تعداد مشخصی پیام بر پایهٔ یک پرس‌وجو. کد زیر نشان می‌دهد چگونه پیام‌ها را لیست کنیم.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an imapclient with host, user and password
ImapClient client = new ImapClient("localhost", "user", "password");

// Select the inbox folder and Get the message info collection
ImapQueryBuilder builder = new ImapQueryBuilder();
MailQuery query = builder
        .or(builder.or(builder.or(builder.or(builder.getSubject().contains(" (1) "), builder.getSubject().contains(" (2) ")), builder.getSubject().contains(" (3) ")),
                builder.getSubject().contains(" (4) ")), builder.getSubject().contains(" (5) "));
ImapMessageInfoCollection messageInfoCol4 = client.listMessages(query, 4);
System.out.println((messageInfoCol4.size() == 4) ? "Success" : "Failure");

لیست کردن پیام‌ها از سرور به صورت بازگشتی

پروتکل IMAP از لیست کردن پیام‌ها به صورت بازگشتی از یک پوشهٔ صندوق پست پشتیبانی می‌کند. این امکان فهرست کردن پیام‌ها از زیرپوشه‌های یک پوشه را نیز فراهم می‌سازد. کد زیر نشان می‌دهد چگونه پیام‌ها را به صورت بازگشتی لیست کنیم.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an imapclient with host, user and password
ImapClient client = new ImapClient();
client.setHost("domain.com");
client.setUsername("username");
client.setPassword("password");
client.selectFolder("InBox");
ImapMessageInfoCollection msgsColl = client.listMessages(true);
System.out.println("Total Messages: " + msgsColl.size());

فهرست‌کردن پیام‌ها با چند‌اتصال

ImapClient ارائه می‌دهد یک UseMultiConnection ویژگی که می‌تواند برای ایجاد چندین اتصال برای عملیات سنگین استفاده شود. همچنین می‌توانید با استفاده از ImapClient.ConnectionsQuantity. کد زیر استفاده از حالت چند‑اتصال برای لیست کردن پیام‌ها را نشان می‌دهد و عملکرد آن را با حالت اتصال تک مقایسه می‌کند.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
ImapClient imapClient = new ImapClient();
imapClient.setHost("<HOST>");
imapClient.setPort(993);
imapClient.setUsername("<USERNAME>");
imapClient.setPassword("<PASSWORD>");
imapClient.setSupportedEncryption(EncryptionProtocols.Tls);
imapClient.setSecurityOptions(SecurityOptions.SSLImplicit);

imapClient.selectFolder("Inbox");
imapClient.setConnectionsQuantity(5);
imapClient.setUseMultiConnection(MultiConnectionMode.Enable);
long multiConnectionModeStartTime = System.currentTimeMillis();
ImapMessageInfoCollection messageInfoCol1 = imapClient.listMessages(true);
long multiConnectionModeTimeSpan = System.currentTimeMillis() - multiConnectionModeStartTime;

imapClient.setUseMultiConnection(MultiConnectionMode.Disable);
long singleConnectionModeStartTime = System.currentTimeMillis();
ImapMessageInfoCollection messageInfoCol2 = imapClient.listMessages(true);
long singleConnectionModeTimeSpan = System.currentTimeMillis() - singleConnectionModeStartTime;

double performanceRelation = singleConnectionModeTimeSpan / multiConnectionModeTimeSpan;
System.out.println("Performance Relation: " + performanceRelation);

دریافت پیام‌ها به ترتیب نزولی

Aspose.Email ارائه می‌دهد ImapClient.listMessagesByPage متد که پیام‌ها را با پشتیبانی از صفحه‌بندی فهرست می‌کند. برخی بارگذاری‌های  ImapClient.listMessagesByPage پذیرش PageSettings به عنوان پارامتر. PageSettings یک  AscendingSorting ویژگی که زمانی که به false تنظیم شود، ایمیل‌ها را به ترتیب نزولی بر می‌گرداند.

کد مثال زیر نحوه استفاده از  AscendingSorting ویژگی PageSettings کلاس برای تغییر ترتیب ایمیل‌ها.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
ImapClient imapClient = new ImapClient();
imapClient.setHost("<HOST>");
imapClient.setPort(993);
imapClient.setUsername("<USERNAME>");
imapClient.setPassword("<PASSWORD>");
imapClient.setSupportedEncryption(EncryptionProtocols.Tls);
imapClient.setSecurityOptions(SecurityOptions.SSLImplicit);

PageSettings pageSettings = new PageSettings();
pageSettings.setAscendingSorting(false);
ImapPageInfo pageInfo = imapClient.listMessagesByPage(5, pageSettings);
ImapMessageInfoCollection messages = pageInfo.getItems();

for (ImapMessageInfo message : messages) {
    System.out.println(message.getSubject() + " -> " + message.getDate().toString());
}

دریافت پیام‌ها از سرور و ذخیره بر روی دیسک

این ImapClient کلاس می‌تواند پیام‌ها را از یک سرور IMAP دریافت کرده و آن‌ها را در قالب EML بر روی دیسک محلی ذخیره کند. مراحل زیر برای ذخیره پیام‌ها بر روی دیسک ضروری است:

  1. یک نمونه از ImapClient کلاس.
  2. در ImapClient، نام میزبان، پورت، نام کاربری و گذرواژه را مشخص کنید constructor.
  3. پوشه را با استفاده از selectFolder() متد.
  4. متد را فراخوانی کنید listMessages متد برای دریافت ImapMessageInfoCollection شیء.
  5. درون ImapMessageInfoCollection مجموعه، فراخوانی کنید saveMessage() متد که مسیر خروجی و نام فایل را تعیین می‌کند.

کد زیر نشان می‌دهد چگونه پیام‌های ایمیل را از یک سرور دریافت و ذخیره کنید.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Select the inbox folder and Get the message info collection
client.selectFolder(ImapFolderInfo.IN_BOX);
ImapMessageInfoCollection list = client.listMessages();

// Download each message
for (int i = 0; i < list.size(); i++) {
    // Save the EML file locally
    client.saveMessage(list.get_Item(i).getUniqueId(), dataDir + list.get_Item(i).getUniqueId() + ".eml");
}

ذخیرهٔ پیام‌ها در قالب MSG

در مثال بالا, ایمیل‌ها در قالب EML ذخیره می‌شوند. برای ذخیره ایمیل‌ها در قالب MSG، ImapClient.fetchMessage() متد باید فراخوانی شود. پیام را در یک نمونه از MailMessage کلاس. MailMessage.save() متد می‌تواند سپس برای ذخیره پیام به فرمت MSG فراخوانی شود. کد زیر نشان می‌دهد چگونه پیام‌ها را در قالب MSG ذخیره کنید.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the file directory.
String dataDir = "data/";

// Create an imapclient with host, user and password
ImapClient client = new ImapClient("localhost", "user", "password");

// Select the inbox folder and Get the message info collection
client.selectFolder(ImapFolderInfo.IN_BOX);
ImapMessageInfoCollection list = client.listMessages();

// Download each message
for (int i = 0; i < list.size(); i++) {
    // Save the message in MSG format
    MailMessage message = client.fetchMessage(list.get_Item(i).getUniqueId());
    message.save(dataDir + list.get_Item(i).getUniqueId() + "_out.msg", SaveOptions.getDefaultMsgUnicode());
}

گروه‌بندی بازیابی پیام‌ها

ImapClient ارائه می‌دهد یک fetchMessages متدی که یک iterable از شماره‌های توالی یا شناسهٔ یکتا می‌پذیرد و فهرستی از MailMessage. قطعه کد زیر استفاده از fetchMessages متد برای بازیابی پیام‌ها بر اساس شماره توالی و شناسهٔ یکتا.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
ImapClient imapClient = new ImapClient();
imapClient.setHost("<HOST>");
imapClient.setPort(993);
imapClient.setUsername("<USERNAME>");
imapClient.setPassword("<PASSWORD>");
imapClient.setSupportedEncryption(EncryptionProtocols.Tls);
imapClient.setSecurityOptions(SecurityOptions.SSLImplicit);

ImapMessageInfoCollection messageInfoCol = imapClient.listMessages();
System.out.println("ListMessages Count: " + messageInfoCol.size());

List<Integer> sequenceNumberAr = new ArrayList<Integer>();
List<String> uniqueIdAr = new ArrayList<String>();
for (ImapMessageInfo mi : messageInfoCol) {
    sequenceNumberAr.add(mi.getSequenceNumber());
    uniqueIdAr.add(mi.getUniqueId());
}

for (MailMessage m : imapClient.fetchMessagesBySequences(sequenceNumberAr)) {
    System.out.println("FetchMessages-sequenceNumberAr : " + m.getSubject());
}

for (MailMessage m : imapClient.fetchMessagesByUids(uniqueIdAr)) {
    System.out.println("FetchMessages-uniqueIdAr : " + m.getSubject());
}

رشته‌بندی ایمیل/سازماندهی ایمیل‌ها به‌صورت گفتگوها

Aspose.Email امکان گروه‌بندی تمام پیام‌های فوروارد، پاسخ و پاسخ به همه‌جا که به همان گفتگو مربوط هستند را به‌صورت سلسله‌مراتبی فراهم می‌کند. در اصل، پروتکل IMAP ممکن است از قابلیت THREAD تعریف‌شده در RFC-5256 پشتیبانی کند. علاوه بر این، افزونه دیگری از IMAP توسط جی‌میل ارائه شده که به عنوان X-GM-EXT-1 توصیف می‌شود.

ویژگی‌های رشته‌بندی ایمیل زیر برای استفاده در دسترس هستند:

  • getMessageThreads متد - رشته‌های پیام را دریافت می‌کند توسط ImapClient.
  • boolean getGmExt1Supported - اطلاعاتی دربارهٔ اینکه آیا افزونه Gmail X-GM-EXT-1 پشتیبانی می‌شود را دریافت می‌کند.
  • boolean getThreadSupported - اطلاعاتی دربارهٔ اینکه آیا افزونه THREAD پشتیبانی می‌شود را دریافت می‌کند.
  • String[] getThreadAlgorithms - الگوریتم‌های THREAD پشتیبانی‌شده را دریافت می‌کند.

نمونه‌های کد زیر نحوه استفاده از این ویژگی‌ها برای دریافت رشته‌های ایمیل از جی‌میل را نشان می‌دهند:

  ImapClient client = new ImapClient("imap.gmail.com", 993, "username", "password", SecurityOptions.SSLImplicit);

try {

    client.selectFolder(ImapFolderInfo.IN_BOX);

   // get a list of messages that we'll group by conversation

   ImapMessageInfoCollection messages = client.listMessages();

   // make sure the IMAP server supports X-GM-EXT-1 extension

   if (client.getGmExt1Supported()) {

       // gets unique conversationId for our example

       Set<String> conversationIds = new HashSet<String>();

       for (ImapMessageInfo messageInfo : messages) {

           if (messageInfo.getConversationId() != null)

                conversationIds.add(messageInfo.getConversationId());

       }

       for (String conversationId : conversationIds) {

           // create the necessary search conditions for a thread

           XGMThreadSearchConditions conditions = new XGMThreadSearchConditions();

            conditions.setConversationId(conversationId);

            conditions.setUseUId(true);

           // get results

           List<MessageThreadResult> conversation = client.getMessageThreads(conditions);

           // print the email conversation in hierarchically manner

           printConversaton("", conversation, messages);

            System.out.println("--------------------");

       }

   }

} finally {

    client.dispose();

}

/**

 * <p>

 * Prints the email conversation in hierarchically manner

 * </p>

 */

public static void printConversaton(String indent, Iterable<MessageThreadResult> conversation,

    Iterable<ImapMessageInfo> messages) {

   for (MessageThreadResult thread : conversation) {

       for (ImapMessageInfo messageInfo : messages) {

           if (thread.getUniqueId().equals(messageInfo.getUniqueId())) {

                System.out.println(indent + " (" + thread.getUniqueId() + ") " + messageInfo.getSubject());

               break;

           }

       }

       if (thread.getChildMessages().size() != 0) {

            printConversaton(indent += "-", thread.getChildMessages(), messages);

       }

   }

}

کد کمی تغییر می‌کند اگر سرور IMAP از قابلیت THREAD پشتیبانی کند:

بررسی کنید آیا سرور IMAP از افزونه THREAD پشتیبانی می‌کند:

 if (client.getThreadSupported())

شرایط جستجوی مناسب برای یک رشته (thread) را ایجاد کنید:

 ThreadSearchConditions conditions = new ThreadSearchConditions();

conditions.setAlgorithm(client.getThreadAlgorithms()[0]);

conditions.setUseUId(true);

لیست‌کردن پیام‌ها با پشتیبانی از صفحه‌بندی

در سناریوهایی که سرور ایمیل تعداد زیادی پیام در صندوق‌پست دارد، معمولاً تمایل به فهرست یا دریافت پیام‌ها با پشتیبانی از صفحه‌بندی وجود دارد. API Aspose.Email ImapClient به شما امکان می‌دهد پیام‌ها را از سرور با پشتیبانی از صفحه‌بندی بازیابی کنید.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// This example shows the paging support of ImapClient for listing messages from the server
// Available in Aspose.Email for Java and onwards
final ImapClient client = new ImapClient("host.domain.com", 993, "username", "password");
try {
    try {
        int messagesNum = 12;
        int itemsPerPage = 5;
        MailMessage message = null;
        // Create some test messages and append these to server's inbox
        for (int i = 0; i < messagesNum; i++) {
            message = new MailMessage("from@domain.com", "to@domain.com", "EMAILNET-35157 - " + UUID.randomUUID(),
                    "EMAILNET-35157 Move paging parameters to separate class");
            client.appendMessage(ImapFolderInfo.IN_BOX, message);
        }

        // List messages from inbox
        client.selectFolder(ImapFolderInfo.IN_BOX);
        ImapMessageInfoCollection totalMessageInfoCol = client.listMessages();
        // Verify the number of messages added
        System.out.println(totalMessageInfoCol.size());

        ////////////////// RETREIVE THE MESSAGES USING PAGING SUPPORT////////////////////////////////////

        List<ImapPageInfo> pages = new ArrayList<ImapPageInfo>();
        PageSettings pageSettings = new PageSettings();
        ImapPageInfo pageInfo = client.listMessagesByPage(itemsPerPage, 0, pageSettings);
        System.out.println(pageInfo.getTotalCount());
        pages.add(pageInfo);
        while (!pageInfo.getLastPage()) {
            pageInfo = client.listMessagesByPage(itemsPerPage, pageInfo.getNextPage().getPageOffset(), pageSettings);
            pages.add(pageInfo);
        }
        int retrievedItems = 0;

        // foreach to while statements conversion
        for (ImapPageInfo folderCol : pages) {
            retrievedItems += folderCol.getItems().size();
        }
        System.out.println(retrievedItems);
    } finally {
    }
} finally {
    if (client != null)
        client.dispose();
}

دریافت پوشه‌ها و خواندن پیام‌ها به‌صورت بازگشتی

در این مقاله، بیشتر ImapClient این ویژگی‌ها برای ایجاد برنامه‌ای استفاده می‌شوند که تمامی پوشه‌ها و زیرپوشه‌ها را به صورت بازگشتی از یک سرور IMAP فهرست می‌کند. همچنین پیام‌های هر پوشه و زیرپوشه را در قالب MSG بر روی دیسک محلی ذخیره می‌کند. در دیسک، پوشه‌ها و پیام‌ها به همان ساختار سلسله‌مراتبی که در سرور IMAP وجود دارد، ساخته و ذخیره می‌شوند. کد زیر نشان می‌دهد چگونه اطلاعات پیام‌ها و زیرپوشه‌ها را به صورت بازگشتی دریافت کنید.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void run() throws Exception {
    // Create an instance of the ImapClient class
    ImapClient client = new ImapClient();

    // Specify host, username, password, Port and SecurityOptions for your client
    client.setHost("imap.gmail.com");
    client.setUsername("your.username@gmail.com");
    client.setPassword("your.password");
    client.setPort(993);
    client.setSecurityOptions(SecurityOptions.Auto);
    try {
        // The root folder (which will be created on disk) consists of host and username
        String rootFolder = client.getHost() + "-" + client.getUsername();

        // Create the root folder and List all the folders from IMAP server
        new File(rootFolder).mkdirs();
        ImapFolderInfoCollection folderInfoCollection = client.listFolders();
        for (ImapFolderInfo folderInfo : folderInfoCollection) {
            // Call the recursive method to read messages and get sub-folders
            listMessagesInFolder(folderInfo, rootFolder, client);
        }
        // Disconnect to the remote IMAP server
        client.dispose();
    } catch (java.lang.RuntimeException ex) {
        System.out.println(ex);
    }

    System.out.println("Downloaded messages recursively from IMAP server.");
}

/// Recursive method to get messages from folders and sub-folders
private static void listMessagesInFolder(ImapFolderInfo folderInfo, String rootFolder, ImapClient client) {
    // Create the folder in disk (same name as on IMAP server)
    String currentFolder = "data/";
    new File(currentFolder).mkdirs();

    // Read the messages from the current folder, if it is selectable
    if (folderInfo.getSelectable()) {
        // Send status command to get folder info
        ImapFolderInfo folderInfoStatus = client.getFolderInfo(folderInfo.getName());
        System.out.println(folderInfoStatus.getName() + " folder selected. New messages: " + folderInfoStatus.getNewMessageCount() + ", Total messages: "
                + folderInfoStatus.getTotalMessageCount());

        // Select the current folder and List messages
        client.selectFolder(folderInfo.getName());
        ImapMessageInfoCollection msgInfoColl = client.listMessages();
        System.out.println("Listing messages....");
        for (ImapMessageInfo msgInfo : msgInfoColl) {
            // Get subject and other properties of the message
            System.out.println("Subject: " + msgInfo.getSubject());
            System.out.println("Read: " + msgInfo.isRead() + ", Recent: " + msgInfo.getRecent() + ", Answered: " + msgInfo.getAnswered());

            // Get rid of characters like ? and :, which should not be included in a file name and Save the message in MSG format
            String fileName = msgInfo.getSubject().replace(":", " ").replace("?", " ");
            MailMessage msg = client.fetchMessage(msgInfo.getSequenceNumber());
            msg.save(currentFolder + "\\" + fileName + "-" + msgInfo.getSequenceNumber() + ".msg", SaveOptions.getDefaultMsgUnicode());
        }
        System.out.println("============================\n");
    } else {
        System.out.println(folderInfo.getName() + " is not selectable.");
    }

    try {
        // If this folder has sub-folders, call this method recursively to get messages
        ImapFolderInfoCollection folderInfoCollection = client.listFolders(folderInfo.getName());
        for (ImapFolderInfo subfolderInfo : folderInfoCollection) {
            listMessagesInFolder(subfolderInfo, rootFolder, client);
        }
    } catch (java.lang.RuntimeException e) {
    }
}

دریافت UID یا شماره ترتیب پیام

API عمومی Aspose.Email ویژگی‌های زیر را برای دریافت اطلاعات شناسایی پیام مانند UID یا شماره ترتیب که ممکن است هنگام پردازش پیام‌های دریافت شده از سرور نیاز باشد، فراهم می‌کند:

MailboxInfo کلاس - نمایانگر اطلاعات شناسایی یک پیام در صندوق پستی.

  • getSequenceNumber() متد - شماره ترتیبی (sequence number) یک پیام را دریافت می‌کند.
  • getUniqueId() متد - شناسه یکتا (unique id) یک پیام را دریافت می‌کند.

MailMessage کلاس - یک پیام ایمیل را نمایندگی می‌کند و امکان دسترسی به ویژگی‌های پیام مانند موضوع، بدنه، فرستنده و آدرس‌های گیرندگان و غیره را فراهم می‌کند.

  • getItemId متد - اطلاعات شناسایی درباره یک پیام در صندوق‌پست را نشان می‌دهد.

نمونه کد زیر نشان می‌دهد که چگونه جزئیات پیام‌ها را از پوشه "INBOX" در یک سرور IMAP با استفاده از ImapClient کلاس:

try (ImapClient client = new ImapClient(imapHost, port, emailAddress, password, securityOption)) {
    ImapMessageInfoCollection msgs = client.listMessages("INBOX");
    List<Integer> seqIds = new ArrayList<>();
    for (ImapMessageInfo msg : msgs) {
        seqIds.add(msg.getSequenceNumber());
    }
    Iterable<MailMessage> msgsViaFetch = client.fetchMessagesBySequences(seqIds);
    for (MailMessage thisMsg : msgsViaFetch) {
        System.out.println("Message ID: " + thisMsg.getItemId().getUniqueId()
                + " SequenceNumber: " + thisMsg.getItemId().getSequenceNumber()
                + " Subject: " + thisMsg.getSubject());
    }
}

بازیابی پارامترهای اضافی به عنوان اطلاعات خلاصه

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
final ImapClient client = new ImapClient("host.domain.com", "username", "password");
try {
    MailMessage message = new MailMessage("from@domain.com", "to@doman.com", "EMAILNET-38466 - " + UUID.randomUUID().toString(),
            "EMAILNET-38466 Add extra parameters for UID FETCH command");

    // append the message to the server
    String uid = client.appendMessage(message);

    // wait for the message to be appended
    Thread.sleep(5000);

    // Define properties to be fetched from server along with the message
    List<String> messageExtraFields = Arrays.asList("X-GM-MSGID", "X-GM-THRID");

    // retreive the message summary information using it's UID
    ImapMessageInfo messageInfoUID = client.listMessage(uid, messageExtraFields);

    // retreive the message summary information using it's sequence number
    ImapMessageInfo messageInfoSeqNum = client.listMessage(1, messageExtraFields);

    // List messages in general from the server based on the defined properties
    ImapMessageInfoCollection messageInfoCol = client.listMessages(messageExtraFields);

    ImapMessageInfo messageInfoFromList = messageInfoCol.get_Item(0);

    // verify that the parameters are fetched in the summary information
    for (String paramName : messageExtraFields) {
        System.out.println(messageInfoFromList.getExtraParameters().containsKey(paramName));
        System.out.println(messageInfoUID.getExtraParameters().containsKey(paramName));
        System.out.println(messageInfoSeqNum.getExtraParameters().containsKey(paramName));
    }
} finally {
    if (client != null)
        client.dispose();
}

دریافت اطلاعات هدر List-Unsubscribe

هدر List-Unsubscribe شامل URL برای لغو اشتراک از لیست‌های ایمیل مانند تبلیغات، خبرنامه‌ها و غیره است. برای دریافت هدر List-Unsubscribe، از listUnsubscribe ویژگی ImapMessageInfo کلاس. مثال زیر نحوه استفاده از آن را نشان می‌دهد listUnsubscribe ویژگی برای دریافت هدر List-Unsubscribe.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
ImapClient imapClient = new ImapClient();
imapClient.setHost("<HOST>");
imapClient.setPort(993);
imapClient.setUsername("<USERNAME>");
imapClient.setPassword("<PASSWORD>");
imapClient.setSupportedEncryption(EncryptionProtocols.Tls);
imapClient.setSecurityOptions(SecurityOptions.SSLImplicit);

ImapMessageInfoCollection messageInfoCol = imapClient.listMessages();
for (ImapMessageInfo imapMessageInfo : messageInfoCol) {
    System.out.println("ListUnsubscribe Header: " + imapMessageInfo.getListUnsubscribe());
}