Làm việc với Thư mục trên máy chủ IMAP

Lấy thông tin Thư mục

Lấy thông tin về các thư mục từ máy chủ IMAP rất dễ dàng với Aspose.Email. Gọi listFolders() phương thức của ImapClient lớp. Nó trả về một đối tượng của ImapFolderInfoCollection kiểu. Lặp qua bộ sưu tập này và lấy thông tin về từng thư mục riêng lẻ trong một vòng lặp. Phương thức được overload. Bạn có thể truyền tên thư mục làm tham số để lấy danh sách các thư mục con. Đoạn mã sau đây cho bạn thấy cách lấy thông tin thư mục từ máy chủ IMAP bằng phương pháp Aspose.Email đã mô tả.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Get all folders in the currently subscribed folder
ImapFolderInfoCollection folderInfoColl = client.listFolders();

// Iterate through the collection to get folder info one by one
for (ImapFolderInfo folderInfo : (Iterable<ImapFolderInfo>) folderInfoColl) {
    // Folder name and get New messages in the folder
    System.out.println("Folder name is " + folderInfo.getName());
    ImapFolderInfo folderExtInfo = client.getFolderInfo(folderInfo.getName());
    System.out.println("New message count: " + folderExtInfo.getNewMessageCount());
    System.out.println("Is it readonly? " + folderExtInfo.getReadOnly());
    System.out.println("Total number of messages " + folderExtInfo.getTotalMessageCount());
}

Xóa và Đổi tên Thư mục

Một thư mục trên máy chủ IMAP có thể được xóa hoặc đổi tên trong một dòng lệnh duy nhất với Aspose.Email:

  • Cái deleteFolder() phương thức chấp nhận tên thư mục làm tham số.
  • Đối với renameFolder() phương thức, bạn cần truyền tên thư mục hiện tại và tên thư mục mới. Đoạn mã sau đây cho bạn thấy cách xóa một thư mục khỏi máy chủ IMAP, và cách đổi tên một thư mục. Mỗi thao tác được thực hiện bằng một dòng lệnh.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Delete a folder and Rename a folder
client.deleteFolder("foldername");
client.renameFolder("foldername", "newfoldername");

Thêm một tin nhắn mới vào thư mục

Bạn có thể thêm một tin nhắn mới vào thư mục bằng cách sử dụng MailMessage và ImapClient lớp. Đầu tiên, tạo một MailMessage đối tượng bằng cách cung cấp các giá trị chủ đề, người nhận và người gửi. Sau đó đăng ký vào một thư mục và thêm tin nhắn vào đó. Đoạn mã sau đây cho bạn thấy cách thêm một tin nhắn mới vào thư mục.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create a message
MailMessage msg = new MailMessage("user@domain1.com", "user@domain2.com", "subject", "message");

// Subscribe to the Inbox folder and Append the newly created message
client.selectFolder(ImapFolderInfo.IN_BOX);
client.subscribeFolder(client.getCurrentFolder().getName());
client.appendMessage(client.getCurrentFolder().getName(), msg);

Thêm nhiều tin nhắn với hỗ trợ MultiConnection

Bạn có thể thêm nhiều tin nhắn bằng cách sử dụng appendMessages phương thức do ImapClient lớp.  appendMessages phương thức chấp nhận một danh sách của MailMessage và thêm nó vào thư mục hiện tại nếu thư mục không được cung cấp làm tham số. ImapClient cũng hỗ trợ chế độ MultiConnection cho các thao tác tải nặng. Đoạn mã sau đây cho bạn thấy cách thêm nhiều tin nhắn bằng cách sử dụng chế độ MultiConnection.

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

List<MailMessage> messages = new ArrayList<MailMessage>();
for (int i = 0; i < 20; i++) {
    MailMessage message = new MailMessage("<EMAIL ADDRESS>", "<EMAIL ADDRESS>", "Test Message - " + UUID.randomUUID().toString(), "IMAP Group Append with MultiConnection");
    messages.add(message);
}

imapClient.setConnectionsQuantity(5);
imapClient.setUseMultiConnection(MultiConnectionMode.Enable);
imapClient.appendMessages(messages);

Di chuyển thư sang Thư mục Hộp thư khác

Aspose.Email for Java cho phép di chuyển một tin nhắn từ một thư mục hộp thư này sang thư mục khác bằng cách sử dụng ImapClient API. The moveMessage phương thức sử dụng ID duy nhất của tin nhắn và tên thư mục đích để di chuyển tin nhắn tới thư mục đích. Đoạn mã dưới đây cho bạn thấy cách di chuyển tin nhắn sang thư mục hộp thư khác.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// This example shows how to move a message from one folder of a mailbox to another one using the ImapClient API of Aspose.Email for Java
// Available from Aspose.Email for Java onwards
// -------------- Available API Overload Members --------------
// void ImapClient.moveMessage(IConnection iConnection, int sequenceNumber, String folderName, boolean commitDeletions)
// void ImapClient.moveMessage(IConnection iConnection, String uniqueId, String folderName, boolean commitDeletions)
// void ImapClient.moveMessage(int sequenceNumber, String folderName, boolean commitDeletions)
// void ImapClient.moveMessage(String uniqueId, String folderName, boolean commitDeletions)
// void ImapClient.moveMessage(IConnection iConnection, int sequenceNumber, String folderName)
// void ImapClient.moveMessage(IConnection iConnection, String uniqueId, String folderName)
// void ImapClient.moveMessage(int sequenceNumber, String folderName)
// void ImapClient.moveMessage(String uniqueId, String folderName)

final ImapClient client = new ImapClient("host.domain.com", 993, "username", "password");
try {
    String folderName = "EMAILNET-35151";
    if (!client.existFolder(folderName))
        client.createFolder(folderName);
    try {
        MailMessage message = new MailMessage("from@domain.com", "to@domain.com", "EMAILNET-35151 - " + UUID.randomUUID(),
                "EMAILNET-35151 ImapClient: Provide option to Move Message");
        client.selectFolder(ImapFolderInfo.IN_BOX);
        // Append the new message to Inbox folder
        String uniqueId = client.appendMessage(ImapFolderInfo.IN_BOX, message);
        ImapMessageInfoCollection messageInfoCol1 = client.listMessages();
        System.out.println(messageInfoCol1.size());
        // Now move the message to the folder EMAILNET-35151
        client.moveMessage(uniqueId, folderName);
        client.commitDeletes();
        // Verify that the message was moved to the new folder
        client.selectFolder(folderName);
        messageInfoCol1 = client.listMessages();
        System.out.println(messageInfoCol1.size());
        // Verify that the message was moved from the Inbox
        client.selectFolder(ImapFolderInfo.IN_BOX);
        messageInfoCol1 = client.listMessages();
        System.out.println(messageInfoCol1.size());
    } finally {
        try {
            client.deleteFolder(folderName);
        } catch (java.lang.RuntimeException e) {
        }
    }
} finally {
    if (client != null)
        client.dispose();
}

Sao chép thư vào Thư mục Hộp thư khác

API Aspose.Email cung cấp khả năng sao chép một tin nhắn từ thư mục hộp thư này sang thư mục hộp thư khác. Nó cho phép sao chép một tin nhắn đơn lẻ cũng như nhiều tin nhắn bằng cách sử dụng copyMessagecopyMessages phương thức. copyMessages phương thức cung cấp khả năng sao chép nhiều tin nhắn từ thư mục nguồn của một hộp thư sang thư mục hộp thư đích. Đoạn mã sau đây cho bạn thấy cách sao chép tin nhắn sang một thư mục hộp thư khác.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
final ImapClient client = new ImapClient("exchange.aspose.com", "username", "password");
try {
    // Create the destination folder
    String folderName = "EMAILNET-35242";
    if (!client.existFolder(folderName))
        client.createFolder(folderName);
    try {
        // Append a couple of messages to the server
        MailMessage message1 = new MailMessage("asposeemail.test3@aspose.com", "asposeemail.test3@aspose.com", "EMAILNET-35242 - " + UUID.randomUUID(),
                "EMAILNET-35242 Improvement of copy method.Add ability to 'copy' multiple messages per invocation.");
        String uniqueId1 = client.appendMessage(message1);

        MailMessage message2 = new MailMessage("asposeemail.test3@aspose.com", "asposeemail.test3@aspose.com", "EMAILNET-35242 - " + UUID.randomUUID(),
                "EMAILNET-35242 Improvement of copy method.Add ability to 'copy' multiple messages per invocation.");
        String uniqueId2 = client.appendMessage(message2);

        // Verify that the messages have been added to the mailbox
        client.selectFolder(ImapFolderInfo.IN_BOX);
        ImapMessageInfoCollection msgsColl = client.listMessages();
        for (ImapMessageInfo msgInfo : msgsColl)
            System.out.println(msgInfo.getSubject());

        // Copy multiple messages using the CopyMessages command and Verify that messages are copied to the destination folder
        client.copyMessagesByUids(Arrays.asList(uniqueId1, uniqueId2), folderName);

        client.selectFolder(folderName);
        msgsColl = client.listMessages();
        for (ImapMessageInfo msgInfo : msgsColl)
            System.out.println(msgInfo.getSubject());
    } finally {
        try {
            client.deleteFolder(folderName);
        } catch (java.lang.RuntimeException e) {
        }
    }
} finally {
    if (client != null)
        client.dispose();
}

Làm việc với các Thư mục Hộp thư Dùng Đặc biệt

Một số kho tin nhắn IMAP bao gồm các hộp thư dùng đặc biệt, chẳng hạn như các hộp lưu bản nháp hoặc tin đã gửi. Nhiều client email cho phép người dùng chỉ định nơi lưu bản nháp hoặc tin đã gửi, nhưng việc cấu hình chúng yêu cầu người dùng biết các hộp thư mà máy chủ đã dành cho các mục đích này. Aspose.Email có thể xác định các hộp thư dùng đặc biệt này bằng cách sử dụng ImapMailboxInfo lớp để làm cho việc làm việc với chúng dễ dàng hơn. Mẫu mã sau đây minh họa cách truy cập các hộp thư dùng đặc biệt này bằng cách sử dụng ImapMailboxInfo lớp.

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

ImapMailboxInfo mailboxInfo = imapClient.getMailboxInfo();
System.out.println(mailboxInfo.getInbox());
System.out.println(mailboxInfo.getDraftMessages());
System.out.println(mailboxInfo.getJunkMessages());
System.out.println(mailboxInfo.getSentMessages());
System.out.println(mailboxInfo.getTrash());