Làm việc với Tin nhắn từ máy chủ IMAP

Liệt kê ID tin nhắn MIME từ máy chủ

ImapMessageInfo cung cấp MIME MessageId để xác định tin nhắn mà không cần trích xuất toàn bộ tin nhắn. Đoạn mã sau cho bạn thấy cách liệt kê MIME messageId.

// 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());
}

Liệt kê Tin nhắn từ Máy chủ

Aspose.Email cung cấp một phiên bản overload 2 thành phần của listMessages() để truy xuất một số lượng tin nhắn xác định dựa trên truy vấn. Đoạn mã sau cho bạn thấy cách liệt kê tin nhắn.

// 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");

Liệt kê Tin nhắn từ Máy chủ Đệ quy

Giao thức IMAP hỗ trợ việc liệt kê tin nhắn đệ quy từ một thư mục hộp thư. Điều này cũng giúp liệt kê tin nhắn từ các thư mục con. Đoạn mã sau cho bạn thấy cách liệt kê tin nhắn một cách đệ quy.

// 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());

Liệt kê Tin nhắn với MultiConnection

ImapClient cung cấp một UseMultiConnection thuộc tính có thể được sử dụng để tạo nhiều kết nối cho các thao tác nặng. Bạn cũng có thể đặt số lượng kết nối sẽ được sử dụng trong chế độ đa kết nối bằng cách sử dụng ImapClient.ConnectionsQuantity. Đoạn mã sau minh họa việc sử dụng chế độ đa kết nối để liệt kê tin nhắn và so sánh hiệu năng của nó với chế độ kết nối đơn.

// 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);

Lấy tin nhắn theo thứ tự giảm dần

Aspose.Email cung cấp ImapClient.listMessagesByPage phương thức liệt kê tin nhắn có hỗ trợ phân trang. Một số overload của ImapClient.listMessagesByPage chấp nhận PageSettings như một tham số. PageSettings cung cấp một AscendingSorting thuộc tính mà khi đặt thành false, trả về email theo thứ tự giảm dần.

Mã ví dụ sau đây minh họa cách sử dụng AscendingSorting thuộc tính của PageSettings lớp để thay đổi thứ tự của email.

// 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());
}

Lấy tin nhắn từ máy chủ và lưu lên đĩa

Cái ImapClient lớp có thể lấy tin nhắn từ máy chủ IMAP và lưu chúng ở định dạng EML lên đĩa cục bộ. Các bước sau đây cần thực hiện để lưu tin nhắn lên đĩa:

  1. Tạo một đối tượng của ImapClient lớp.
  2. Xác định hostname, cổng, tên người dùng và mật khẩu trong ImapClient constructor.
  3. Chọn thư mục bằng cách sử dụng selectFolder() phương thức.
  4. Gọi listMessages phương thức để lấy ImapMessageInfoCollection đối tượng.
  5. Lặp qua ImapMessageInfoCollection bộ sưu tập, gọi saveMessage() phương thức và cung cấp đường dẫn đầu ra cùng tên tệp.

Đoạn mã sau đây cho bạn thấy cách lấy các tin nhắn email từ máy chủ và lưu chúng.

// 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");
}

Lưu Tin nhắn ở Định dạng MSG

Trong ví dụ trên, các email được lưu ở định dạng EML. Để lưu email ở định dạng MSG, ImapClient.fetchMessage() phương thức cần được gọi. Nó trả về tin nhắn dưới dạng một thể hiện của MailMessage lớp. MailMessage.save() phương thức sau đó có thể được gọi để lưu tin nhắn thành MSG. Đoạn mã sau đây cho bạn thấy cách lưu tin nhắn ở định dạng 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());
}

Lấy nhiều tin nhắn nhóm

ImapClient cung cấp một fetchMessages phương thức nhận một iterable của Số thứ tự hoặc ID duy nhất và trả về một danh sách của MailMessage. Đoạn mã sau minh họa việc sử dụng fetchMessages phương thức để lấy tin nhắn bằng Số thứ tự và ID duy nhất.

// 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());
}

Phân luồng Email/Tổ chức Email thành các Cuộc trò chuyện

Aspose.Email cho phép nhóm tất cả các tin nhắn chuyển tiếp, trả lời và trả lời tất cả liên quan đến cùng một cuộc trò chuyện lại với nhau theo cách phân cấp. Cơ bản, giao thức IMAP có thể hỗ trợ khả năng THREAD được định nghĩa trong RFC-5256. Ngoài ra, còn có một phần mở rộng IMAP khác do Gmail cung cấp và được mô tả là X-GM-EXT-1.

Các tính năng phân luồng email sau đây có sẵn để sử dụng:

  • getMessageThreads phương thức - Nhận các chuỗi hội thoại tin nhắn bằng ImapClient.
  • boolean getGmExt1Supported - Lấy thông tin xem phần mở rộng Gmail X-GM-EXT-1 có được hỗ trợ hay không.
  • boolean getThreadSupported - Lấy thông tin xem phần mở rộng THREAD có được hỗ trợ hay không.
  • String[] getThreadAlgorithms - Lấy các thuật toán THREAD được hỗ trợ.

Các mẫu mã sau đây cho thấy cách sử dụng các tính năng này để lấy chuỗi hội thoại email từ Gmail:

  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);

       }

   }

}

Mã sẽ hơi thay đổi nếu máy chủ IMAP hỗ trợ khả năng THREAD:

Kiểm tra xem máy chủ IMAP có hỗ trợ phần mở rộng THREAD không:

 if (client.getThreadSupported())

Tạo các điều kiện tìm kiếm phù hợp cho một chuỗi hội thoại:

 ThreadSearchConditions conditions = new ThreadSearchConditions();

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

conditions.setUseUId(true);

Liệt kê Tin nhắn với Hỗ trợ Phân trang

Trong các kịch bản, khi máy chủ email chứa một số lượng lớn tin nhắn trong hộp thư, thường muốn liệt kê hoặc lấy các tin nhắn với hỗ trợ phân trang. API Aspose.Email ImapClient cho phép bạn lấy các tin nhắn từ máy chủ với hỗ trợ phân trang.

// 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();
}

Lấy Thư mục và Đọc Tin nhắn Đệ quy

Trong bài viết này, phần lớn các ImapClient các tính năng được sử dụng để tạo một ứng dụng liệt kê tất cả các thư mục và thư mục con một cách đệ quy từ máy chủ IMAP. Nó cũng lưu các tin nhắn trong mỗi thư mục và thư mục con ở định dạng MSG trên đĩa cứng cục bộ. Trên đĩa, các thư mục và tin nhắn được tạo và lưu theo cùng cấu trúc phân cấp như trên máy chủ IMAP. Đoạn mã sau đây cho bạn thấy cách lấy thông tin các tin nhắn và thư mục con một cách đệ quy.

// 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) {
    }
}

Lấy UID hoặc Số Thứ Tự của Tin Nhắn

API công cộng Aspose.Email cung cấp các tính năng sau để lấy thông tin nhận dạng tin nhắn như UID hoặc số thứ tự, có thể cần thiết khi xử lý các tin nhắn nhận từ máy chủ:

MailboxInfo lớp - Đại diện cho thông tin nhận dạng của một tin nhắn trong hộp thư.

  • getSequenceNumber() phương thức - Lấy số thứ tự của một tin nhắn.
  • getUniqueId() phương thức - Lấy ID duy nhất của một tin nhắn.

MailMessage lớp - Đại diện cho một tin nhắn email và cho phép truy cập các thuộc tính của tin nhắn, ví dụ: tiêu đề, nội dung, người gửi và địa chỉ người nhận, v.v.

  • getItemId phương thức - Đại diện cho thông tin nhận dạng về một tin nhắn trong hộp thư.

Mẫu mã dưới đây minh họa cách lấy và hiển thị chi tiết các tin nhắn từ thư mục "INBOX" trên máy chủ IMAP bằng cách sử dụng ImapClient lớp:

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());
    }
}

Truy xuất các tham số bổ sung dưới dạng thông tin tóm tắt

// 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();
}

Lấy thông tin tiêu đề List-Unsubscribe

Tiêu đề List-Unsubscribe chứa URL để hủy đăng ký các danh sách email như quảng cáo, bản tin, v.v. Để lấy tiêu đề List-Unsubscribe, sử dụng listUnsubscribe thuộc tính của ImapMessageInfo lớp. Ví dụ sau đây cho thấy cách sử dụng listUnsubscribe thuộc tính để lấy tiêu đề 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());
}