소개
이메일 메시지를 프로그래밍 방식으로 파싱하는 것은 데이터 마이그레이션, 보관 워크플로우, 규정 준수 도구에서 일반적인 요구 사항입니다. Outlook MSG 파일은 메시지 메타데이터, 본문 내용, 수신자 및 첨부 파일을 인코딩하기 위해 MAPI 속성을 포함한 Compound File Binary (CFB) 컨테이너 형식을 사용합니다. Python에서 이 형식을 다루려면 전통적으로 상용 라이브러리나 저수준 바이너리 조작이 필요했습니다.
aspose-email-foss 패키지는 순수 Python 기반이며 MIT 라이선스인 라이브러리를 제공하여 Outlook MSG 파일을 읽고, 생성하고, 변환할 수 있습니다. 이 라이브러리는 일반 작업을 위한 고수준 MapiMessage API와 기본 CFB 구조를 상세히 검사할 수 있는 저수준 MsgReader 접근을 모두 제공합니다. 이 라이브러리는 Python 3.10 이상을 필요로 하며 네이티브 종속성이 없습니다.
보관된 메시지 배치에서 제목 줄과 본문을 추출하거나, 인덱싱을 위해 첨부 파일을 열거하거나, MSG 파일을 표준 RFC 5322 형식으로 변환해야 할 경우에도, 이 라이브러리가 바이너리 파싱을 처리하므로 애플리케이션 로직에 집중할 수 있습니다.
포함 내용
MapiMessage를 사용한 MSG 파일 읽기
MapiMessage 클래스는 Outlook MSG 파일을 파싱하기 위한 주요 진입점입니다. 파일을 열고, 속성에 접근한 뒤, 컨텍스트 매니저를 사용해 깔끔하게 닫을 수 있습니다.
from aspose.email_foss import msg
with msg.MapiMessage.from_file("meeting-invite.msg") as message:
print(f"Subject: {message.subject}")
print(f"Body: {message.body[:200]}")
print(f"HTML body available: {message.body_html is not None}")
The from_file 메서드는 CFB 컨테이너를 읽고, MAPI 속성 스트림을 파싱하며, 타입이 지정된 속성을 채웁니다. subject, body, body_html 속성은 디코딩된 문자열을 직접 반환합니다.
수신자 추출
모든 MSG 파일은 전용 MAPI 저장소에 수신자 정보를 저장합니다. MapiMessage.recipients 속성은 표시 이름, 이메일 주소 및 수신자 유형(TO, CC, BCC)을 위한 타입이 지정된 필드를 가진 MapiRecipient 객체 리스트를 반환합니다.
from aspose.email_foss import msg
with msg.MapiMessage.from_file("team-update.msg") as message:
for recipient in message.recipients:
print(
f"{recipient.display_name} <{recipient.email_address}> "
f"type={recipient.recipient_type}"
)
첨부 파일 작업
iter_attachments_info 메서드는 파일 이름, 원시 바이트, MIME 타입, 그리고 인라인 이미지용 선택적 Content-ID를 제공하는 MapiAttachment 객체를 반환합니다.
from aspose.email_foss import msg
with msg.MapiMessage.from_file("report.msg") as message:
for att in message.iter_attachments_info():
print(f" {att.filename} ({att.mime_type}, {len(att.data)} bytes)")
if att.content_id:
print(f" inline content-id: {att.content_id}")
MAPI 속성 접근
편리 속성을 넘어 특정 MAPI 속성 값을 필요로 하는 경우, get_property_value를 PropertyId 상수와 함께 사용하십시오. 이렇게 하면 MSG 파일에 저장된 모든 속성에 직접 접근할 수 있습니다.
from aspose.email_foss import msg
with msg.MapiMessage.from_file("notification.msg") as message:
sender = message.get_property_value(msg.PropertyId.SENDER_NAME)
email = message.get_property_value(msg.PropertyId.SENDER_EMAIL_ADDRESS)
delivery = message.get_property_value(msg.PropertyId.MESSAGE_DELIVERY_TIME)
print(f"From: {sender} <{email}>")
print(f"Delivered: {delivery}")
모든 속성 순회
메시지의 모든 속성을 검사해야 할 때(디버깅, 감시, 또는 마이그레이션을 위해), iter_properties 메서드는 전체 태그와 값 정보를 포함한 MapiProperty 객체를 반환합니다.
from aspose.email_foss import msg
with msg.MapiMessage.from_file("sample.msg") as message:
for prop in message.iter_properties():
print(
f"tag=0x{prop.property_tag:08X} "
f"type=0x{prop.property_type:04X} "
f"value={prop.value!r}"
)
MSG를 EML로 변환
to_email_message 메서드는 파싱된 MSG를 표준 Python email.message.EmailMessage 객체로 변환합니다. 여기에서 표준 라이브러리를 사용하여 메시지를 RFC 5322 (EML) 형식으로 직렬화할 수 있습니다.
from aspose.email_foss import msg
with msg.MapiMessage.from_file("archive.msg") as message:
email_message = message.to_email_message()
eml_bytes = email_message.as_bytes()
with open("archive.eml", "wb") as f:
f.write(eml_bytes)
EML 출력은 Python의 내장 email 모듈을 사용하여 직렬화한다는 점에 유의하십시오. 이 라이브러리는 MSG-to-MAPI-to-EmailMessage 변환을 처리하고; 표준 라이브러리는 RFC 5322 와이어 형식을 처리합니다.
빠른 시작
PyPI에서 패키지를 설치하고 20줄 이하로 첫 번째 MSG 파일을 파싱하십시오:
# Install: pip install aspose-email-foss>=26.3
from aspose.email_foss import msg
# Create a new message
message = msg.MapiMessage.create(
"Project status update",
"Hello team,\n\nPlease review the attached report.\n\nRegards",
)
message.add_recipient("alice@example.com", display_name="Alice")
message.add_attachment("notes.txt", b"meeting notes\n", mime_type="text/plain")
message.save("status-update.msg")
# Read it back and extract data
with msg.MapiMessage.from_file("status-update.msg") as loaded:
print(f"Subject: {loaded.subject}")
print(f"Recipients: {len(loaded.recipients)}")
for att in loaded.iter_attachments_info():
print(f"Attachment: {att.filename} ({len(att.data)} bytes)")
지원되는 형식
| 형식 | 확장자 | 읽기 | 쓰기 |
|---|---|---|---|
| Outlook MSG | .msg | 예 | 예 |
| Compound File Binary | .cfb | 예 | 예 |
| EML (변환을 통해) | .eml | 예 (from_email_message을 통해) | 예 (to_email_message을 통해) |
EML 지원은 변환을 통해 작동합니다: MapiMessage.from_email_message()는 Python email.message.EmailMessage 객체에서 가져오고, to_email_message()는 다시 내보냅니다. 직접적인 EML 파일 파싱은 제공되지 않으며 — 표준 라이브러리가 EML 와이어 형식을 처리합니다.
오픈 소스 및 라이선스
Aspose.Email FOSS for Python는 MIT 라이선스 하에 공개되었습니다. 상업용 및 비상업용 프로젝트 모두에서 라이브러리를 자유롭게 사용, 수정 및 배포할 수 있습니다. 전체 소스 코드는 GitHub에서 확인할 수 있습니다.
이 라이브러리는 pure-Python 구현으로, 컴파일된 확장이나 네이티브 종속성이 없습니다. Python 3.10 이상을 지원하는 모든 플랫폼에서 실행됩니다.
시작하기
Aspose.Email FOSS for Python 작업을 위한 추가 리소스를 살펴보세요:
- Developer Guide — 튜토리얼 및 API 워크스루가 포함된 전체 문서
- Knowledge Base — 사용 방법 기사와 자주 묻는 질문
- API Reference — 전체 클래스 및 메서드 레퍼런스