소개

Aspose.Email FOSS for Python는 기본 메시지 생성 기능을 넘어섭니다. 이 라이브러리는 MAPI 속성 모델의 전체 깊이를 공개하여 ID와 유형별로 개별 속성을 읽고, 쓰고, 쿼리할 수 있게 합니다. 수신자, 첨부 파일 및 임베디드 메시지를 일급 객체로 처리하며, MSG 바이너리 형식과 Python 표준 email.message.EmailMessage 간의 양방향 변환을 제공합니다.

컨테이너 수준에서 CFB 리더와 라이터는 Compound File Binary 문서에 대한 결정적인 제어를 제공합니다. 저장소 계층 구조를 탐색하고, 원시 스트림 데이터를 추출하며, 처음부터 새로운 컨테이너를 구축하고, 이를 바이트로 다시 직렬화할 수 있습니다. CFBErrorMsgError 모두 잘못된 입력에 대한 구조화된 예외 처리를 제공합니다.

이 게시물은 라이브러리 자체 테스트 스위트와 예제 스크립트에서 직접 추출한 검증된 코드 예제를 통해 각 기능을 단계별로 안내합니다.


포함 내용

MAPI 속성 액세스

모든 MSG 파일은 MAPI 속성을 기반으로 구축됩니다. MapiMessageset_property()get_property()를 노출하여 속성을 PropertyId 열거형 값으로 작업할 수 있게 합니다. 메시지의 모든 속성을 열거하려면 iter_properties()를 사용하고, 선택적 유형 디코딩이 가능한 직접 값 검색을 위해서는 get_property_value()를 사용하십시오.

from aspose.email_foss import msg

message = msg.MapiMessage.create("Status report", "Weekly update attached.")

message.set_property(msg.PropertyId.SENDER_NAME, "Build Agent")
message.set_property(msg.PropertyId.SENDER_EMAIL_ADDRESS, "build.agent@example.com")
message.set_property(msg.PropertyId.DISPLAY_TO, "Alice Example; Bob Example")
message.set_property(msg.PropertyId.DISPLAY_CC, "Carol Example")
message.set_property(msg.PropertyId.DISPLAY_BCC, "Ops Archive")
message.set_property(
    msg.PropertyId.TRANSPORT_MESSAGE_HEADERS,
    "X-Environment: production\nX-Workflow: weekly-report\n",
)
message.save("report.msg")

기존 파일에서 속성을 다시 읽으려면:

from aspose.email_foss import msg

with msg.MapiMessage.from_file("report.msg") as loaded:
    print(f"Subject: {loaded.subject}")
    print(f"Body: {loaded.body}")

    for prop in loaded.iter_properties():
        print(f"tag=0x{prop.property_tag:08X}")

수신자 및 첨부 파일

add_recipient()을 사용하여 수신자를 추가하고, 표시 이름 및 수신자 유형(To, CC 또는 BCC)을 지정합니다. add_attachment()을 사용하여 원시 바이트와 MIME 유형으로 파일을 첨부합니다. 중첩 메시지의 경우, add_embedded_message_attachment()은 완전한 MapiMessage을 부모 안의 자식 객체로 삽입합니다.

from aspose.email_foss import msg

message = msg.MapiMessage.create("Team update", "See attached notes.")

message.add_recipient("alice@example.com", display_name="Alice Example")
message.add_recipient(
    "carol@example.com",
    display_name="Carol Example",
    recipient_type=msg.RECIPIENT_TYPE_CC,
)
message.add_recipient(
    "archive@example.com",
    display_name="Ops Archive",
    recipient_type=msg.RECIPIENT_TYPE_BCC,
)

message.add_attachment("notes.txt", b"Meeting notes content\n", mime_type="text/plain")
message.add_attachment("data.bin", b"\x00\x01\x02\x03", mime_type="application/octet-stream")
message.save("team-update.msg")

기존 메시지의 첨부 파일을 검사하려면:

from aspose.email_foss import msg

with msg.MapiMessage.from_file("team-update.msg") as loaded:
    for att in loaded.iter_attachments_info():
        print(f"name={att.filename} mime={att.mime_type} size={len(att.data)}")
        print(f"  embedded={att.is_embedded_message} storage={att.storage_name}")

MSG to EmailMessage 변환

이 라이브러리는 MSG와 Python의 email.message.EmailMessage 사이를 양방향으로 변환합니다. to_email_message()을 사용하여 표준을 준수하는 MIME 객체를 생성하거나, from_email_message()를 사용하여 기존 EmailMessage를 MSG 형식으로 가져올 수 있습니다. 편리한 메서드 to_email_bytes()to_email_string()은 직접 바이트 또는 텍스트로 직렬화합니다.

from aspose.email_foss import msg

with msg.MapiMessage.from_file("example.msg") as loaded:
    email_msg = loaded.to_email_message()

    print(f"content_type: {email_msg.get_content_type()}")
    print(f"is_multipart: {email_msg.is_multipart()}")
    print(f"headers: {len(email_msg)}")

    for key, value in email_msg.items():
        print(f"  {key}: {value}")

    body_part = email_msg.get_body(preferencelist=("plain", "html"))
    if body_part is not None:
        print(f"body: {body_part.get_content()[:200]}")

CFB Container 라운드 트립

MSG 레이어와 독립적으로 Compound File Binary 컨테이너를 빌드하고 직렬화합니다. CFBDocument.from_file()은 기존 컨테이너를 CFBStorageCFBStream 노드와 함께 변경 가능한 문서 모델로 로드합니다. CFBWriter.write_file()은 문서를 디스크에 결정적으로 직렬화합니다.

from aspose.email_foss.cfb import CFBDocument, CFBReader, CFBWriter

reader = CFBReader.from_file("container.cfb")
document = CFBDocument.from_reader(reader)
reader.close()

output = CFBWriter.to_bytes(document)
print(f"Serialized {len(output)} bytes")

오류 처리

라이브러리는 잘못된 CFB 콘텐츠에 대해 CFBError를 발생시키고, 잘못된 MSG 구조에 대해 MsgError를 발생시킵니다. MapiMessage는 또한 예외를 발생시키지 않고 경고 문자열의 튜플을 반환하는 validation_issues 속성을 노출하여, 비준수 파일을 얼마나 엄격하게 처리할지 결정할 수 있게 합니다.

from aspose.email_foss.cfb import CFBReader, CFBError
from aspose.email_foss.msg import MsgReader, MsgError

try:
    reader = CFBReader.from_file("corrupted.cfb")
except CFBError as e:
    print(f"CFB parse error: {e}")

try:
    reader = MsgReader.from_file("malformed.msg")
except MsgError as e:
    print(f"MSG parse error: {e}")

빠른 시작

pip install aspose-email-foss>=26.3

기존 MSG를 로드하고 메타데이터를 읽은 후 첨부 파일을 나열합니다:

from aspose.email_foss import msg

with msg.MapiMessage.from_file("inbox-message.msg") as message:
    print(f"Subject: {message.subject}")
    print(f"Body preview: {message.body[:200] if message.body else '(empty)'}")

    for att in message.iter_attachments_info():
        print(f"Attachment: {att.filename} ({att.mime_type}, {len(att.data)} bytes)")

    issues = message.validation_issues
    if issues:
        print(f"Warnings: {issues}")

지원되는 형식

형식가져오기내보내기
MSG
CFB

오픈 소스 및 라이선스

Aspose.Email FOSS for Python은 MIT License에 따라 릴리스되었습니다. 개인, 내부 및 상업 프로젝트에서 제한 없이 사용할 수 있습니다. 소스 코드는 GitHub에서 확인할 수 있습니다.


시작하기