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 메서드는 소스 폴더의 여러 메시지를 메일함 내 대상 폴더로 전송합니다. 아래 코드는 폴더 간 메시지 복사 방법을 보여줍니다:

특수용도 메일함 폴더 작업

특수용도 메일함은 Sent, Drafts, Junk, Trash, Archive와 같이 특정 종류의 메시지를 처리하도록 설계된 이메일 시스템의 사전 정의 폴더입니다. 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)