在 Python 中管理 IMAP 服务器上的文件夹

列出 IMAP 文件夹

使用 Aspose.Email 从 IMAP 服务器检索文件夹信息非常简单。请按照以下步骤获取并处理文件夹详情:

  1. 使用 Aspose.Email 的 list_folders() 方法 ImapClient 类。此方法返回一个实例 ImapFolderInfoCollection,其中包含所有文件夹的详细信息。
  2. 循环遍历 ImapFolderInfoCollection 用于访问各个文件夹信息的对象。
  3. 检索子文件夹(可选)。list_folders() 方法被重载。可以将文件夹名称作为参数传入,以检索指定文件夹的子文件夹集合。

下面的代码片段演示了如何使用 Aspose.Email 方法从 IMAP 服务器检索文件夹信息:

重命名和删除文件夹

Aspose.Email 提供了以下方法: ImapClient 用于通过 IMAP 管理邮件服务器上文件夹的类:

  • delete_folder 方法 - 永久删除文件夹及其包含的所有邮件。
  • rename_folder 方法 - 更改文件夹名称而不修改其中的内容。

下面的代码片段展示了如何在 IMAP 服务器上以编程方式删除或重命名文件夹:

# Delete a folder and Rename a folder
client.delete_folder("foldername")
client.rename_folder("foldername", "newfoldername")

创建并添加邮件到特定文件夹

使用 Aspose.Email API,您可以使用 MailMessageImapClient 类,用于向文件夹添加新邮件。首先,创建一个 MailMessage 对象,指定主题、发件人和收件人。然后,订阅文件夹并将邮件添加进去。下面的代码片段演示了如何向文件夹添加新邮件:

  1. 使用以下方式初始化 IMAP 客户端 ImapClient 用于连接邮件服务器的类。提供服务器地址、端口、用户名和密码。
  2. 使用 select_folder 方法选择要添加新邮件的目标文件夹,例如 "Inbox"。
  3. 使用以下方式创建新邮件 MailMessage 类。指定发件人、收件人、主题和邮件内容。
  4. 使用 subscribe_folder 方法并提供文件夹名称来订阅该文件夹。
  5. 使用 append_message 方法将新创建的邮件添加到所选文件夹,指定文件夹名称和邮件对象。

在文件夹之间移动邮件

Aspose.Email for .NET 允许使用以下方式将邮件从一个邮箱文件夹移动到另一个: ImapClient API。move_message 方法使用邮件的唯一 ID 和目标文件夹名称,将邮件移动到目标文件夹。以下代码片段展示了如何在文件夹之间移动邮件:

在文件夹之间复制邮件

Aspose.Email API 可轻松实现将邮件从一个邮箱文件夹复制到另一个。可以使用 copy_messagecopy_messages 方法复制单封或多封邮件。copy_messages 方法允许将多个邮件从源文件夹传输到邮箱内的目标文件夹。以下代码片段演示了如何在文件夹之间复制邮件:

使用特殊用途邮箱文件夹

特殊用途邮箱是电子邮件系统中预定义的文件夹,用于处理特定类型的邮件,如已发送、草稿、垃圾邮件、垃圾箱和存档。Aspose.Email 库通过将属性与这些文件夹的角色和用途关联,简化了对它们的访问。这使得客户端能够自动发现并显示这些文件夹,无需任何用户干预。

下面的代码片段演示了如何使用该类的属性检索关键特殊用途邮箱(收件箱、草稿、垃圾邮件、已发送和垃圾箱)的信息 ImapMailBoxInfo 类,并打印详细信息:

import aspose.email as ae

client = ae.clients.imap.ImapClient("imap.domain.com", 993, "user@domain.com", "pwd", ae.clients.SecurityOptions.SSL_IMPLICIT)

mailboxInfo = client.mailbox_info
print(mailboxInfo.inbox)
print(mailboxInfo.draft_messages)
print(mailboxInfo.junk_messages)
print(mailboxInfo.sent_messages)
print(mailboxInfo.trash)

递归访问文件夹并读取邮件

ImapClient 使用递归方法列出 IMAP 服务器上的文件夹和子文件夹。此方法亦用于以 MSG 格式读取并保存邮件到本地磁盘。文件夹和邮件均按在 IMAP 服务器上的层级结构创建和保存。以下代码片段演示了如何递归检索文件夹和邮件:

import aspose.email as ae
import os

# Recursive method to get messages from folders and sub-folders
def list_messages_in_folder(folder_info, root_folder, client):
    # Create the folder on disk (same name as on the IMAP server)
    current_folder = os.path.join(root_folder, folder_info.name)
    os.makedirs(current_folder, exist_ok=True)

    # Read the messages from the current folder, if it is selectable
    if folder_info.selectable:
        # Send a status command to get folder info
        folder_info_status = client.get_folder_info(folder_info.name)
        print(
            f"{folder_info_status.name} folder selected. New messages: {folder_info_status.new_message_count}, "
            f"Total messages: {folder_info_status.total_message_count}"
        )

        # Select the current folder and list messages
        client.select_folder(folder_info.name)
        msg_info_coll = client.list_messages()
        print("Listing messages....")
        for msg_info in msg_info_coll:
            # Get subject and other properties of the message
            print("Subject:", msg_info.subject)
            print(
                f"Read: {msg_info.is_read}, Recent: {msg_info.recent}, Answered: {msg_info.answered}"
            )

            # Get rid of characters like ? and :, which should not be included in a file name
            # Save the message in MSG format
            file_name = (
                msg_info.subject.replace(":", " ").replace("?", " ")
                + "-"
                + str(msg_info.sequence_number)
                + ".msg"
            )
            msg = client.fetch_message(msg_info.sequence_number)
            msg.save(
                os.path.join(current_folder, file_name),
                ae.SaveOptions.default_msg_unicode,
            )
        print("============================\n")
    else:
        print(f"{folder_info.name} is not selectable.")

    try:
        # If this folder has sub-folders, call this method recursively to get messages
        folder_info_collection = client.list_folders(folder_info.name)
        for subfolder_info in folder_info_collection:
            list_messages_in_folder(subfolder_info, root_folder, client)
    except Exception:
        pass



client = ae.clients.imap.ImapClient("imap.domain.com", 993, "user@domain.com", "pwd", ae.clients.SecurityOptions.SSL_IMPLICIT)

try:
    # The root folder (which will be created on disk) consists of host and username
    root_folder = f"{client.host}-{client.username}"

    # Create the root folder and list all the folders from the IMAP server
    os.makedirs(root_folder, exist_ok=True)
    folder_info_collection = client.list_folders()
    for folder_info in folder_info_collection:
        # Call the recursive method to read messages and get sub-folders
        list_messages_in_folder(folder_info, root_folder, client)
except Exception as ex:
        print("\n", ex)

print("\nDownloaded messages recursively from IMAP server.")

使用 MultiConnection 批量文件夹操作

Aspose.Email 使客户端能够配置为与 IMAP 服务器建立多个并发连接。虽然不一定提升性能,但它是并发操作的可靠方案。特别适用于客户端需要同时执行多项任务的场景,如获取不同邮件文件夹、同步大量数据或同时处理多封邮件。

下面的代码片段展示了在使用该类的 ‘append_messages’ 方法上传邮件集合时,如何建立到 IMAP 服务器的多个连接: ImapClient 类:

import aspose.email as ae

client = ae.clients.imap.ImapClient("imap.domain.com", 993, "user@domain.com", "pwd", ae.clients.SecurityOptions.SSL_IMPLICIT)

client.connections_quantity = 5
client.use_multi_connection = ae.clients.MultiConnectionMode.ENABLE
client.append_messages(messages)