IMAP 서버에서 이메일 가져오고 나열하기

메일함에서 메시지 목록

’list_messages’ 메서드 ImapClient 클래스는 현재 선택된 폴더(이 경우 "Inbox")에서 모든 메시지 목록을 가져옵니다. 이 목록은 메시지 ID, 시퀀스 번호, UID 및 경우에 따라 제목이나 발신자 정보와 같은 요약 데이터를 포함하는 메시지 메타데이터 객체를 포함합니다.

아래 코드 스니펫은 받은편지함에서 메시지 메타데이터를 가져와 전체 메시지 수를 출력하는 방법을 보여줍니다:

import aspose.email as ae

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

client.select_folder("Inbox")

messages = client.list_messages()
print(f"Total Messages: {len(messages)}")

페이지 지원을 통한 메시지 목록

메일함에 대량의 메시지가 있는 경우, 페이지 지원을 통해 메시지를 나열하거나 검색하는 것이 일반적입니다. Aspose.Email은 ImapClient 클래스는 페이지 지원을 통해 서버에서 메시지를 검색할 수 있게 합니다.

재귀적으로 메시지 나열

IMAP 프로토콜은 메일함 폴더의 메시지를 재귀적으로 나열할 수 있게 하며, 하위 폴더의 메시지까지 나열이 가능합니다. 아래 코드 스니펫은 메시지를 재귀적으로 나열하는 방법을 보여줍니다:

MIME Message ID 목록

다음은 ImapMessageInfo 클래스는 전체 메시지 내용을 추출하지 않고도 메시지를 식별하기 위해 MIME MessageId에 접근하는 편리한 방법을 제공합니다. 아래 코드는 MIME MessageId를 나열하는 예시입니다:

다중 연결을 통한 메시지 목록

다음은 ImapClient 클래스는 use_multi_connection 속성을 제공하여 고부하 작업에 다중 연결을 사용할 수 있게 합니다. 또한 connections_quantity 속성을 사용해 다중 연결 모드에서 연결 수를 지정할 수 있습니다. 아래 코드 스니펫은 메시지 목록을 위해 다중 연결 모드를 활용하는 방법을 보여줍니다:

import aspose.email as ae

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

client.select_folder("Inbox")
client.connections_quantity = 5
client.use_multi_connection = ae.clients.MultiConnectionMode.ENABLE

message_info_col = client.list_messages(True)

이 모드를 사용한다고 반드시 성능이 향상되는 것은 아니라는 점에 유의하십시오.

시퀀스 번호 또는 고유 ID로 메시지 검색

Aspose.Email API를 사용하면 시퀀스 번호 목록과 받은편지함의 모든 메시지 고유 ID 목록 두 개를 생성할 수 있습니다. 식별자를 통해 IMAP 서버에서 메시지를 가져오려면 해당 클래스의 fetch_messages 메서드를 사용하십시오 ImapClient 클래스. 아래 코드 스니펫은 식별자를 사용해 메시지를 나열하는 방법을 보여줍니다:

import aspose.email as ae

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

# List messages
message_info_col = client.list_messages()
print("ListMessages Count:", message_info_col.count)

# Get sequence numbers and unique IDs
sequence_number_ar = [mi.sequence_number for mi in message_info_col]
unique_id_ar = [mi.unique_id for mi in message_info_col]

# Fetch messages by sequence number
fetched_messages_by_snum = client.fetch_messages(sequence_number_ar)
print("FetchMessages-sequenceNumberAr Count:", len(fetched_messages_by_snum))

# Fetch messages by UID
fetched_messages_by_uid = client.fetch_messages(unique_id_ar)
print("FetchMessages-uniqueIdAr Count:", len(fetched_messages_by_uid))

내림차순으로 메시지 가져오기

이 작업은 메시지 검색을 위한 페이지 설정을 정의함으로써 달성됩니다. 이를 위해 해당 클래스의 ascending_sorting 속성을 사용하십시오 PageSettings IMAP 클라이언트 모듈의 일부인 클래스입니다. ascending_sorting 속성을 설정하십시오 PageSettings 객체를 False로 설정합니다. 이는 기본적으로 메시지를 내림차순으로 정렬하여 가져옴을 의미합니다. 아래 코드 스니펫은 내림차순으로 메시지를 가져오는 방법을 보여줍니다:

import aspose.email as ae

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

page_settings = ae.clients.imap.PageSettings
page_settings.ascending_sorting = False
page_info = client.list_messages_by_page(5, page_settings)
messages = page_info.items

for message in messages:
    print(message.subject)

서버에서 메시지를 가져와 디스크에 저장

다음은 ImapClient 클래스는 IMAP 서버에서 메시지를 가져와 EML 형식으로 로컬 디스크에 저장할 수 있습니다. 메시지를 디스크에 저장하려면 다음 단계가 필요합니다:

  1. 다음 사용 ImapClient IMAP 서버에 연결하기 위해 필요한 매개변수(호스트, 포트, 사용자 이름, 비밀번호)를 가진 클래스.
  2. select_folder 메서드(예: "Inbox")를 호출하여 원하는 폴더를 선택합니다
  3. list_messages 메서드를 사용해 메시지를 순회하면서 가져옵니다.
  4. 메시지를 저장하려면 각 메시지에 대해 디렉터리를 지정하고 고유 ID를 파일 이름에 추가하는 save_message 메서드를 사용하십시오.

다음 코드 스니펫은 서버에서 이메일 메시지를 가져와 저장하는 방법을 보여줍니다:

MSG 형식으로 메시지 저장

MSG 형식으로 이메일을 저장하려면 해당 클래스의 fetch_message 메서드를 호출하십시오. ImapClient 클래스. 해당 클래스는 메시지를 다음 인스턴스로 반환합니다 MailMessage 클래스. MailMessage.save() 메서드를 호출하면 메시지를 MSG 형식으로 저장할 수 있습니다. 아래 코드 스니펫은 MSG 형식으로 메시지를 저장하는 방법을 보여줍니다.

추가 메시지 파라미터(요약 정보) 가져오기

아래 코드 스니펫은 Aspose.Email을 사용해 이메일 서버와 상호 작용하는 방법을 보여줍니다 ImapClient 이메일 메시지를 전송하고 조작하기 위해 사용됩니다. 코드는 메시지 UID를 사용해 추가 파라미터("X-GM-MSGID", "X-GM-THRID")와 함께 요약 정보를 가져옵니다. 시퀀스 번호를 사용해 유사한 정보를 가져올 수도 있습니다.

List-Unsubscribe 헤더 가져오기

"ListUnsubscribe" 헤더는 메일링 리스트 또는 자동 이메일 시스템에서 발송된 이메일 메시지 헤더에 일반적으로 포함됩니다. 이는 수신자가 메일링 리스트 또는 자동 이메일 구독을 해지할 수 있는 링크 또는 이메일 주소를 제공합니다. Aspose.Email은 ’list_unsubscribe’ 속성을 제공합니다. ImapMessageInfo 이 헤더를 검색하는 클래스. 아래 코드 스니펫은 해당 속성의 사용 방법을 보여주며, 원치 않는 이메일의 구독 해지를 자동화하는 시스템의 일부로 사용할 수 있습니다:

import aspose.email as ae

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

message_info_col = client.list_messages()

# Iterate through each message
for imap_message_info in message_info_col:
    print("ListUnsubscribe Header:", imap_message_info.list_unsubscribe)

메시지 식별 정보 가져오기

이메일 메시지를 검색하고 처리할 때, 시퀀스 번호를 사용해 메시지 상세 정보를 가져올 수 있습니다.

다음 기능을 사용해 IMAP 메일함과 상호 작용합니다:

아래 코드 스니펫은 메시지 식별 정보를 얻는 방법을 보여줍니다:

import aspose.email as ae

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

msg_infos = client.list_messages("INBOX")

for msg_info in msg_infos:
    # fetch by sequence number
    msg = client.fetch_message(msg_info.sequence_number)

    # fetch by unique id
    msg = client.fetch_message(msg_info.unique_id)

IMAP 이메일 메시지의 첨부 파일 목록

첨부 파일 데이터를 가져오지 않고 이름, 크기와 같은 정보를 얻으려면 다음 라이브러리 리소스를 사용하십시오:

아래 코드 샘플은 Aspose.Email을 사용해 각 이메일 메시지의 첨부 파일을 나열하는 방법을 보여줍니다 ImapClient:

# List messages
message_info_col = client.list_messages()

# Iterate through each message
for message_info in message_info_col:
    print(f"Attachments for message with sequence number {message_info.sequence_number}:")

    # List attachments for the current message
    attachment_info_col = client.list_attachments(message_info.sequence_number)

    # Iterate through each attachment
    for attachment_info in attachment_info_col:
        print(f"Attachment: {attachment_info.name} (size: {attachment_info.size})")