Outlook 메시지에서 첨부 파일 관리
다음은 Outlook 메시지(MSG) 파일 만들기 및 저장 이 문서는 메시지를 생성하고 저장하는 단계(첨부 파일이 포함된 MSG 파일 포함)를 설명했습니다. 이 문서는 Aspose.Email을 사용한 Microsoft Outlook 첨부 파일 관리에 대해 자세히 다룹니다. 메시지 파일에서 첨부 파일에 접근하고 저장하는 방법을 안내합니다 attachments 속성 MapiMessage 클래스. 이 속성은 다음에 속한 컬렉션입니다 MapiAttachmentCollection 클래스는 첨부 파일을 효율적으로 처리할 수 있게 합니다.
인라인 vs 일반 첨부 파일 확인
"Inline" 및 "Regular" 첨부 파일은 이메일 메시지에 포함되는 방식을 의미합니다. Regular 첨부 파일은 전통적인 방식으로 파일이 첨부되는 것으로, 일반적으로 이메일 클라이언트 내 리스트에 표시되어 수신자가 다운로드하여 로컬에 저장할 수 있습니다. Inline 첨부 파일은 임베드된 이미지나 미디어로, 이메일 본문에 직접 표시됩니다. 별도 리스트에 표시되지 않고 이메일 내용 안에 바로 보여집니다. 이를 통해 메시지 내용의 일부인 이미지나 미디어를 포함할 수 있습니다. 아래 코드 샘플은 첨부 파일이 인라인인지 일반인지 판단하는 방법을 보여줍니다:
import aspose.email as ae
msg = ae.mapi.MapiMessage.load("message.msg")
for attachment in msg.attachments:
print(f"{attachment.display_name}:{attachment.is_inline}")
MAPI 메시지에서 참조 첨부 파일 식별
Aspose.Email API에는 is_reference 속성 MapiAttachment 클래스는 개발자가 메시지에서 참조 첨부 파일을 식별할 수 있게 합니다. 아래 코드 샘플을 통해 파이썬 프로젝트에서 어떻게 동작하는지 확인해 보세요:
import aspose.email as ae
# Load or create a MapiMessage
msg = ae.mapi.MapiMessage.load("Message_With_Reference_Attachment.msg")
# Iterate through the attachments
for attachment in msg.attachments:
if attachment.is_reference:
# Process reference attachment
pass
MSG 파일에서 첨부 파일 저장
MSG 파일에서 첨부 파일을 저장하려면:
- 다음에 대해 반복합니다 MapiAttachmentCollection 컬렉션을 사용하여 개별 첨부 파일을 가져옵니다.
- 첨부 파일을 저장하려면 다음을 호출하십시오 MapiAttachment 클래스 Save() 메서드.
다음 코드 조각은 첨부 파일을 로컬 디스크에 저장하는 방법을 보여줍니다:
import aspose.email as ae
# Create an instance of MapiMessage from file
message = ae.mapi.MapiMessage.load(data_dir + "message.msg")
# Iterate through the attachments collection
for attachment in message.attachments:
# Save the individual attachment
attachment.save(data_dir + attachment.long_file_name)
TNEF 첨부 파일 처리
TNEF 형식으로 첨부 파일 로드 및 저장
Aspose.Email은 TNEF 첨부 파일을 처리하기 위한 메서드를 제공합니다. 이러한 메서드를 사용하면 일반적으로 Outlook 메시지에서 사용되는 TNEF 형식(예: winmail.dat)으로 첨부 파일을 저장하고 로드할 수 있습니다.
- static MapiAttachment MapiAttachment.load_from_tnef(string fileName) – TNEF 파일에서 첨부 파일을 로드합니다.
- static MapiAttachment MapiAttachment.load_from_tnef(Stream stream) – TNEF 스트림에서 첨부 파일을 로드합니다.
- void MapiAttachment.save_to_tnef(string filename) – 첨부 파일을 TNEF 파일에 저장합니다.
- void MapiAttachment.save_to_tnef(Stream stream) – 첨부 파일을 TNEF 스트림에 저장합니다.
다음 코드 샘플은 메모리 스트림 또는 파일을 통해 TNEF 형식 이메일 첨부 파일을 추출, 저장 및 재추가하는 방법을 보여줍니다:
import io
from aspose.email.mapi import MapiMessage, MapiAttachment
# Load the EML message (which contains a winmail.dat TNEF attachment)
msg = MapiMessage.load("message.eml")
# Save the first attachment as a winmail.dat file
msg.attachments[0].save_to_tnef("winmail.dat")
# Load the TNEF attachment from the file and add it back to the message
from_tnef_attachment = MapiAttachment.load_from_tnef("winmail.dat")
msg.attachments.add(from_tnef_attachment.long_file_name, from_tnef_attachment.binary_data)
# (Optional) If you also want to use a memory stream instead of the file
ms = io.BytesIO()
msg.attachments[0].save_to_tnef(ms)
# Reset the stream position to the beginning
ms.seek(0)
# Load the TNEF attachment directly from the memory stream and add it
from_tnef_attachment_from_stream = MapiAttachment.load_from_tnef(ms)
msg.attachments.add(from_tnef_attachment_from_stream.long_file_name, from_tnef_attachment_from_stream.binary_data)
중첩된 메일 메시지 첨부 파일 검색
포함된 OLE(객체 연결 및 포함) 첨부 파일 또한 해당의 첨부 파일 컬렉션에 나타납니다 MapiMessage 클래스. 아래 코드 예제는 메시지 파일을 파싱하고 포함된 메시지 첨부 파일을 추출한 뒤, 이를 디스크에 저장하여 후속 사용을 가능하게 하는 방법을 보여줍니다. 해당 MapiMessage 클래스는 from_properties 정적 메서드는 포함된 첨부 파일에서 새 메시지를 생성합니다. 다음 코드 조각은 중첩된 메일 메시지 첨부 파일을 가져오는 방법을 보여줍니다:
import aspose.email as ae
eml = ae.mapi.MapiMessage.load("my.msg")
for index, attachment in enumerate(eml.attachments):
# Only the embedded messages carry OLE object data
if attachment.object_data is None:
continue
# Create a MapiMessage object from the individual attachment
get_attachment = ae.mapi.MapiMessage.from_properties(attachment.object_data.properties)
# Convert the embedded message to a MailMessage and save it to disk
mail_message = get_attachment.to_mail_message(ae.mapi.MailConversionOptions())
mail_message.save(f"NestedMailMessageAttachments_{index}_out.eml", ae.SaveOptions.default_eml)
첨부 파일 제거
Aspose.Email 라이브러리는 Microsoft Outlook 메시지(.msg) 파일에서 첨부 파일을 제거하는 기능을 제공합니다. 다음을 사용하십시오 remove_attachments(path) 경로를 매개변수로 요구하는 메서드입니다. 퍼블릭 정적 메서드이므로 객체를 인스턴스화하지 않고 바로 호출할 수 있어 프로세스가 간단하고 효율적입니다.
다음 코드 조각은 Aspose.Email을 사용하여 MSG 파일에서 첨부 파일을 제거하는 방법을 보여줍니다:
import aspose.email as ae
ae.mapi.MapiMessage.remove_attachments("AttachmentsToRemove_out.msg")
또한 정적 destroy_attachments 메서드를 호출할 수 있습니다 MapiMessage 클래스. remove_attachments보다 더 빠르게 작동합니다. 왜냐하면 remove_attachments 메서드는 메시지 파일을 파싱하기 때문입니다.
import aspose.email as ae
# Destroy attachments in the MapiMessage
ae.mapi.MapiMessage.destroy_attachments("AttachmentsToDestroy_out.msg")
MSG 첨부 파일 추가
Outlook 메시지는 다른 Microsoft Outlook 메시지를 정규 첨부 파일이나 포함된 첨부 파일로 포함할 수 있습니다. 해당 MapiAttachmentCollection 다음의 오버로드된 멤버를 제공합니다 추가 두 종류의 첨부 파일을 모두 포함하는 Outlook 메시지를 생성하는 메서드.
사용해 보세요!
무료로 온라인에서 이메일 첨부 파일을 추가하거나 제거하세요 Aspose.Email Editor App.
새로 추가된 첨부 파일에 접근
다음은 추가 메서드 MapiAttachmentCollection 클래스는 MapiAttachment 생성된 객체를 반환합니다. 이를 통해 새 첨부 파일에 바로 접근하여 삽입 직후에 구성할 수 있으며, 컬렉션을 검색할 필요가 없습니다. 일반 첨부 파일을 바이트에서, Outlook 메시지를 임베디드 첨부 파일로, 또는 참조 첨부 파일을 추가하던지 생성된 첨부 파일이 반환됩니다.
다음 코드 샘플은 일반 첨부 파일과 임베디드 메시지를 추가하고 표시 이름을 변경합니다:
import aspose.email as ae
message = ae.mapi.MapiMessage("from@domain.com", "to@domain.com", "Weekly report", "Please find the files attached.")
# Add a regular attachment and change its display name
with open("invoice.pdf", "rb") as f:
attachment = message.attachments.add("invoice.pdf", f.read())
attachment.display_name = "Invoice #2026-001.pdf"
# Add an embedded message and change its display name
embedded = message.attachments.add("original.msg", ae.mapi.MapiMessage.load("message.msg"))
embedded.display_name = "Original request"
message.save("report.msg")
MAPI 메시지에 참조 첨부 파일 추가
Reference attachment는 실제 파일 대신 외부 리소스에 대한 참조나 링크를 포함하는 첨부 파일을 의미합니다. 이러한 참조는 HTML 이메일에서 외부 이미지나 원격 서버에 호스팅된 리소스에 연결할 때 자주 사용됩니다. 전체 파일을 포함하는 대신 URL이나 외부 콘텐츠에 대한 참조를 포함합니다.
MAPI 메시지에 참조 첨부 파일을 추가하려면 다음을 사용하십시오 add 메서드 MapiAttachmentCollection class와 ReferenceAttachmentOptions 지정할 클래스:
-
콘텐츠 URL(파일에 대한 직접 링크)
-
제공자 URL(파일 위치 또는 UI 뷰에 대한 링크)
-
첨부 파일 제공자 이름(예: "GoogleDrive")
아래 코드 샘플에 표시된 대로.
import aspose.email as ae
# Load or create a MapiMessage
msg = ae.mapi.MapiMessage()
msg.subject = "Email with Reference Attachment"
msg.body = "This message contains a cloud-based reference attachment."
# Create ReferenceAttachmentOptions
options = ae.mapi.ReferenceAttachmentOptions(
"https://drive.google.com/file/d/1HJ-M3F2qq1oRrTZ2GZhUdErJNy2CT3DF/",
"https://drive.google.com/drive/my-drive",
"GoogleDrive"
)
# Add the reference attachment to the message
msg.attachments.add("Document.pdf", options)
# Save the message to MSG format
msg.save("Message_With_Reference_Attachment.msg")
메시지를 첨부 파일로 포함
다음 코드 조각은 Outlook MSG 파일을 다른 MSG 파일에 첨부 파일로 포함하는 방법을 보여줍니다. 포함된 MSG 파일은 PR_ATTACH_METHOD 속성이 5로 설정되어 있어 "message" 유형의 첨부 파일임을 나타냅니다.
import aspose.email as ae
# Create a new MapiMessage
message = ae.mapi.MapiMessage("from@test.com", "to@test.com", "Subj", "This is a message body")
# Load the attachment message
attach_msg = ae.mapi.MapiMessage.load("Message.msg")
# Add the attachment to the message
message.attachments.add("Weekly report.msg", attach_msg)
# Save the message with the embedded message attachment
message.save("WithEmbeddedMsg_out.msg")
첨부 파일에서 포함된 메시지 읽기
다음 코드 조각은 첨부 파일에서 포함된 메시지를 읽는 방법을 보여줍니다.
import aspose.email as ae
file_name = "path/to/file.msg"
# Load the MapiMessage from file
message = ae.mapi.MapiMessage.load(file_name)
# Check if the first attachment is an Outlook message
if message.attachments[0].object_data.is_outlook_message:
# Get the embedded message as MapiMessage
embedded_message = message.attachments[0].object_data.to_mapi_message()
# Perform further operations with the embedded message
# ...
첨부 파일 삽입 및 교체
Aspose.Email API는 상위 메시지 내 특정 인덱스에 첨부 파일을 삽입하는 기능을 제공합니다. 또한 기존 첨부 파일의 내용을 다른 메시지 첨부 파일로 교체할 수도 있습니다. 아래 코드는 첨부 파일 삽입 및 교체 방법을 보여줍니다.
특정 위치에 첨부 파일 삽입
Aspose.Email은 부모 MSG에 MSG 첨부 파일을 삽입할 수 있게 합니다. insert() 메서드 MapiAttachmentCollection 클래스, 삽입할 인덱스, 첨부 파일 이름 및 MapiMessage 첨부하려면. 아래는 특정 위치에 첨부 파일을 삽입하는 방법을 보여주는 코드 스니펫입니다:
import aspose.email as ae
from io import BytesIO
file_name = "path/to/file.msg"
# Load the MapiMessage from file
message = ae.mapi.MapiMessage.load(file_name)
# Save the attachment to a memory stream
memory_stream = BytesIO()
message.attachments[2].save(memory_stream)
# Load the attachment from the memory stream
get_data = ae.mapi.MapiMessage.load(memory_stream)
# Insert the loaded attachment at index 1
message.attachments.insert(1, "new 11", get_data)
첨부 파일 내용 교체
다음을 사용할 수 있습니다 replace 새 데이터로 삽입된 첨부 파일의 내용을 업데이트하는 메서드입니다. 그러나 이 메서드는 PR_ATTACH_NUM = 4인 첨부 파일을 2개의 첨부 파일만 보유하는 컬렉션에 삽입하는 데 사용할 수 없음을 유의하십시오. 아래는 첨부 파일 내용을 교체하는 방법을 보여주는 코드 스니펫입니다:
import aspose.email as ae
from io import BytesIO
file_name = "path/to/file.msg"
# Load the MapiMessage from file
message = ae.mapi.MapiMessage.load(file_name)
# Save the attachment to a memory stream
memory_stream = BytesIO()
message.attachments[2].save(memory_stream)
# Load the attachment from the memory stream
get_data = ae.mapi.MapiMessage.load(memory_stream)
# Replace the attachment at index 1 with the loaded attachment
message.attachments.replace(1, "new 1", get_data)
MapiMessage에서 첨부 파일 이름 바꾸기
Aspose.Email을 사용하면 파일에서 로드한 이메일 메시지의 첨부 파일 표시 이름을 쉽게 수정할 수 있습니다. 다음 코드 샘플은 이를 수행하는 방법을 보여줍니다:
import aspose.email as ae
msg = ae.mapi.MapiMessage.load("message.msg")
msg.attachments[0].display_name = "New display name 1"
msg.attachments[1].display_name = "New display name 2"
RTF 형식 MSG 파일에서 첨부 파일 추출
RTF로 형식화된 메시지의 경우, 아래 코드는 인라인이거나 아이콘으로 표시되는 첨부 파일을 구분하고 추출합니다. 정보는 첨부 파일의 OLE 객체 데이터에 저장되며, 이는 다음을 통해 접근할 수 있습니다 object_data 속성 MapiAttachment:
- 그
\x03ObjInfo속성은 객체가 인라인으로 표시되는지 아이콘으로 표시되는지를 알려줍니다; - 그
Package속성은 삽입된 파일의 원시 콘텐츠를 보관합니다.
from aspose.email.mapi import MapiMessage
def is_attachment_inline(attachment):
if attachment.object_data is None:
return False
# `values` is a property of MapiPropertyCollection, not a method
for prop in attachment.object_data.properties.values:
if prop.name == "\x03ObjInfo":
odt_persist1 = int.from_bytes(prop.data[:2], "little")
return (odt_persist1 & (1 << 6)) == 0
return False
def save_attachment(attachment, file_name):
for prop in attachment.object_data.properties.values:
if prop.name == "Package":
with open(file_name, "wb") as f:
f.write(prop.data)
msg = MapiMessage.load(data_dir + "MSG file with RTF Formatting.msg")
for index, attachment in enumerate(msg.attachments):
if is_attachment_inline(attachment):
save_attachment(attachment, data_dir + f"attachment_{index}")
oledata.mso에서 포함된 OLE 객체 추출
때때로 포함된 OLE 데이터가 oledata.mso 첨부 파일을 MapiAttachment 수동으로 추출해야 합니다. oledata.mso 파일은 Microsoft Compound Document File(MCDF) 형식이며, 이러한 파일에 대한 지원은 Aspose.Email 범위를 벗어납니다. 그러나 복합 파일 라이브러리와 함께 사용하면 내용을 읽고 디스크에 저장할 수 있습니다.
패키지의 원시 바이트는 다음을 통해 사용할 수 있습니다 binary_data 속성 MapiAttachment 객체. 이를 디스크에 쓰거나, 다음과 같은 복합 파일 읽기 라이브러리로 직접 전달할 수 있습니다 olefile, 삽입된 객체에 접근하려면.
메시지 본문 형식이 HTML(RTF가 아님)이고 메시지에 OLE 객체가 포함된 경우 PR_ATTACH_DATA_OBJ 속성이 없습니다. 이 경우 OLE 객체에 대한 정보가 다음에 포함됩니다 oledata.mso.
from aspose.email.mapi import MapiMessage
msg = MapiMessage.load(data_dir + "double.msg")
for mapi_attachment in msg.attachments:
if mapi_attachment.long_file_name == "oledata.mso":
# The package is a compound file: save it and read its streams with a
# library such as olefile
with open(data_dir + "oledata.mso", "wb") as f:
f.write(mapi_attachment.binary_data)