이메일 로드, 저장 및 변환
이메일 파일 형식 감지
Aspose.Email API는 제공된 메시지 파일의 파일 형식을 감지하는 기능을 제공합니다. The DetectFileFormat 메서드 FileFormatUtil 클래스를 사용하여 이를 달성할 수 있습니다. 다음 클래스와 메서드를 사용하여 로드된 파일 형식을 감지할 수 있습니다:
- 열거형 FileFormatType
- 클래스 FileFormatInfo
- 클래스 FileFormatUtil
- 메서드 detect_file_format(stream)
- 메서드 detect_file_format(file_path)
다음 코드 스니펫은 파일 형식을 감지하는 방법을 보여줍니다:
from aspose.email.tools import FileFormatUtil
# Detect file format and get the detected load format
info = FileFormatUtil.detect_file_format(data_dir + "message.msg")
print("The message format is: " + str(info.file_format_type))
로드 옵션을 사용하여 메시지 로드
다음 코드 스니펫은 로드 옵션을 사용하여 메시지를 로드하는 방법을 보여줍니다.
from aspose.email import MailMessage, EmlLoadOptions, HtmlLoadOptions, MhtmlLoadOptions, MsgLoadOptions
# Load Eml, html, mhtml, msg, and dat files
mail_message = MailMessage.load(data_dir + "message.eml", EmlLoadOptions())
MailMessage.load(data_dir + "description.html", HtmlLoadOptions())
MailMessage.load(data_dir + "message.mhtml", MhtmlLoadOptions())
MailMessage.load(data_dir + "message.msg", MsgLoadOptions())
# Loading with custom options
eml_load_options = EmlLoadOptions()
eml_load_options.preferred_text_encoding = "utf-8"
eml_load_options.preserve_tnef_attachments = True
MailMessage.load(data_dir + "description.html", eml_load_options)
html_load_options = HtmlLoadOptions()
html_load_options.preferred_text_encoding = "utf-8"
html_load_options.should_add_plain_text_view = True
html_load_options.path_to_resources = data_dir
MailMessage.load(data_dir + "description.html", html_load_options)
로드 중에 포함된 메시지 형식 보존
from aspose.email import MailMessage, EmlLoadOptions, HtmlLoadOptions, MhtmlLoadOptions, MsgLoadOptions
from aspose.email.tools import FileFormatUtil
eml_load_options = EmlLoadOptions()
eml_load_options.preserve_embedded_message_format = True
mail = MailMessage.load(data_dir + "message.eml", eml_load_options)
file_format = FileFormatUtil.detect_file_format(mail.attachments[0].content_stream).file_format_type
print("Embedded message file format: " + str(file_format))
이메일 저장 및 변환
Aspose.Email를 사용하면 모든 메시지 유형을 다른 형식으로 쉽게 변환할 수 있습니다. 이 기능을 보여주기 위해 이 문서의 코드는 디스크에서 세 종류의 메시지를 로드하고 다른 형식으로 다시 저장합니다. 기본 클래스 SaveOptions 및 클래스 EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions 다른 형식으로 메시지를 저장할 때 추가 설정에 사용할 수 있습니다. 이 문서는 이러한 클래스를 사용하여 샘플 이메일을 다음과 같이 저장하는 방법을 보여줍니다:
- EML 형식.
- Outlook MSG.
- MHTML 형식.
- HTML 형식.
EML로 저장
다음 코드 스니펫은 EML 메시지를 로드하고 동일한 형식으로 디스크에 저장하는 방법을 보여줍니다.
from aspose.email import MailMessage, SaveOptions
# Initialize and Load an existing EML file by specifying the MessageFormat
mail_message = MailMessage.load(data_dir + "message.eml")
mail_message.save(data_dir + "LoadAndSaveFileAsEML_out.eml", SaveOptions.default_eml)
EML 파일에서 경계 보존
다음 코드 스니펫은 원본 경계를 보존하면서 EML 파일을 로드하고 동일한 형식으로 저장하는 방법을 보여줍니다.
from aspose.email import MailMessage, EmlSaveOptions, MailMessageSaveType
mail_message = MailMessage.load(data_dir + "message.eml")
# Save as eml with preserved original boundaries
eml_save_options = EmlSaveOptions(MailMessageSaveType.eml_format)
mail_message.save(data_dir + "PreserveOriginalBoundaries_out.eml", eml_save_options)
MIME 경계 문자열 맞춤화
Aspose.Email for .NET은 MIME 메시지에 사용되는 경계 템플릿을 구성할 수 있게 해줍니다. 이는 다음을 통해 구현됩니다 boundaries_template 속성 EmlSaveOptions 클래스.
사용자 정의 템플릿을 설정하면 MIME 경계가 생성되는 방식을 정의할 수 있습니다. 템플릿의 {#} 와일드카드는 증가하는 경계 번호로 대체되어 동적이고 읽기 쉬운 경계 문자열을 만들 수 있습니다.
If boundaries_template 설정되지 않으면(기본값은 None), 라이브러리는 내부 경계 형식을 사용합니다.
다음 코드 샘플은 이메일 메시지를 .eml 형식으로 저장할 때 MIME 경계 문자열을 맞춤 설정하는 방법을 보여줍니다:
import aspose.email as ae
# Create a sample MailMessage
message = ae.MailMessage()
message.subject = "Custom MIME Boundary"
message.body = "This message uses a custom MIME boundary template."
message.to.append(ae.MailAddress("recipient@example.com"))
# Configure save options with a custom boundary template
save_options = ae.EmlSaveOptions(ae.MailMessageSaveType.EML_FORMAT)
save_options.boundaries_template = "boundary--{#}"
# Save the message to .eml with custom boundaries
message.save("Custom_Boundary_Message.eml", save_options)
위의 코드를 사용하여 저장된 사용자 정의 경계가 적용된 메시지 구조 예시는 다음과 같습니다:
From: sender@example.com
To: recipient@example.com
Subject: Custom_Boundary_Message
Date: Fri, 27 Dec 2024 12:00:00 +0000
Content-Type: multipart/mixed;
boundary="boundary--1"
This is a multi-part message in MIME format.
--boundary--1
Content-Type: multipart/alternative; boundary="boundary--2"
--boundary--2
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain; charset="us-ascii"
This is the plain text content of the email.
--boundary--2
Content-Type: text/html; charset="windows-1251"
Content-Transfer-Encoding: quoted-printable
<html>
<body>
<p>This is the <b>HTML</b> content of the email.</p>
</body>
</html>
--boundary--2--
--boundary--1
Content-Type: application/octet-stream; name="report-2023-08.xlsx"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="report-2023-08.xlsx"
UEsDBBQABgAIAAAAIQBi7...
--boundary--1--
EML 파일에서 TNEF 첨부 파일 보존
다음 코드 스니펫은 TNEF 첨부 파일을 보존하면서 EML 파일을 저장하는 방법을 보여줍니다.
from aspose.email import MailMessage, EmlSaveOptions, MailMessageSaveType, FileCompatibilityMode
mail_message = MailMessage.load(data_dir + "message.eml")
# Save as eml with preserved attachment
eml_save_options = EmlSaveOptions(MailMessageSaveType.eml_format)
eml_save_options.file_compatibility_mode = FileCompatibilityMode.PRESERVE_TNEF_ATTACHMENTS
mail_message.save(data_dir + "PreserveTNEFAttachment_out.eml", eml_save_options)
MSG로 저장
다음 코드 스니펫은 적절한 옵션을 사용하여 EML 메시지를 로드하고 MSG로 변환하는 방법을 보여줍니다 SaveOptions.
from aspose.email import MailMessage, SaveOptions, MailMessageSaveType, FileCompatibilityMode
# Initialize and Load an existing EML file by specifying the MessageFormat
eml = MailMessage.load(data_dir + "message.eml")
# Save the Email message to disk in ASCII format and Unicode format
eml.save(data_dir + "AnEmail_out.msg", SaveOptions.default_msg_unicode)
MSG 파일에서 날짜 보존
다음은 MsgSaveOptions class를 사용하면 소스 메시지를 날짜를 보존한 채 Outlook Message 파일(MSG)로 저장할 수 있습니다. 다음 코드 스니펫은 EML 파일을 MSG로 저장하고 날짜를 보존하는 방법을 보여줍니다.
from aspose.email import MailMessage, MsgSaveOptions, MailMessageSaveType, FileCompatibilityMode
# Initialize and Load an existing EML file by specifying the MessageFormat
eml = MailMessage.load(data_dir + "message.eml")
# Save as msg with preserved dates
msg_save_options = MsgSaveOptions(MailMessageSaveType.outlook_message_format_unicode)
msg_save_options.preserve_original_dates = True
eml.save(data_dir + "outTest_out.msg", msg_save_options)
MHTML로 저장
원하는 결과를 얻기 위해 다양한 MHTML 옵션을 사용할 수 있습니다. 다음 코드 스니펫은 EML 메시지를 로드하는 방법을 보여줍니다: MailMessage 그리고 MHTML로 변환합니다.
from aspose.email import MailMessage, SaveOptions, MailMessageSaveType, FileCompatibilityMode
# Initialize and Load an existing EML file by specifying the MessageFormat
eml = MailMessage.load(data_dir + "message.eml")
eml.save(data_dir + "AnEmail_out.mhtml", SaveOptions.default_mhtml)
맞춤형 MHTML 변환 설정
다음은 MhtSaveOptions 이 클래스는 이메일 메시지를 MHTML 형식으로 저장하기 위한 추가 옵션을 제공합니다. 열거형 MhtFormatOptions 추가 이메일 정보를 출력 MHTML에 기록할 수 있게 합니다. 다음 추가 필드를 기록할 수 있습니다:
- NONE - 특정 설정이 지정되지 않음.
- WRITE_HEADER - 헤더 정보를 기록해야 함을 나타냅니다.
- WRITE_OUTLINE_ATTACHMENTS - 개요 첨부 파일을 기록해야 함을 나타냅니다.
- WRITE_COMPLETE_EMAIL_ADDRESS - 모든 이메일 헤더에 전체 이메일 주소를 기록해야 함을 나타냅니다.
- NO_ENCODE_CHARACTERS - 문자 전송 인코딩을 사용하지 않아야 함을 나타냅니다.
- HIDE_EXTRA_PRINT_HEADER - PageHeader가 보이지 않게 됩니다.
- WRITE_COMPLETE_TO_EMAIL_ADDRESS - ‘To’ 헤더에 전체 이메일 주소를 기록해야 함을 나타냅니다.
- WRITE_COMPLETE_FROM_EMAIL_ADDRESS - ‘From’ 헤더에 전체 이메일 주소를 기록해야 함을 나타냅니다.
- WRITE_COMPLETE_CC_EMAIL_ADDRESS - ‘Cc’ 헤더에 전체 이메일 주소를 기록해야 함을 나타냅니다.
- WRITE_COMPLETE_BCC_EMAIL_ADDRESS - ‘Bcc’ 헤더에 전체 이메일 주소를 기록해야 함을 나타냅니다.
- RENDER_CALENDAR_EVENT - 캘린더 이벤트의 텍스트가 출력 mhtml에 기록되어야 함을 나타냅니다.
- SKIP_BYTE_ORDER_MARK_IN_BODY - Byte Order Mark(BOM) 바이트를 본문에 기록해야 함을 나타냅니다.
- RENDER_V_CARD_INFO - VCard AlternativeView의 텍스트가 출력 mhtml에 기록되어야 함을 나타냅니다.
- DISPLAY_AS_OUTLOOK - From 헤더가 Outlook처럼 표시된다는 것을 나타냅니다.
- RENDER_TASK_FIELDS - 특정 작업 필드를 출력 mhtml에 기록해야 함을 나타냅니다.
다음 코드 스니펫은 선택적 설정으로 EML 파일을 MHTML로 변환하는 방법을 보여줍니다.
from aspose.email import MailMessage, MhtSaveOptions, MhtFormatOptions, MailMessageSaveType, FileCompatibilityMode
# Load an existing EML file
eml = MailMessage.load(data_dir + "message.eml")
# Save as mht with header
mht_save_options = MhtSaveOptions()
# Specify formatting options required
# Here we are specifying to write header information to output without writing extra print header
# and the output headers should be displayed as the original headers in the message
mht_save_options.mht_format_options = MhtFormatOptions.WRITE_HEADER | MhtFormatOptions.HIDE_EXTRA_PRINT_HEADER | MhtFormatOptions.DISPLAY_AS_OUTLOOK
# Check the body encoding for validity.
mht_save_options.check_body_content_encoding = True
eml.save(data_dir + "outMessage_out.mht", mht_save_options)
MHTML 변환에 캘린더 이벤트 포함
다음은 MhtFormatOptions.RenderCalendarEvent 캘린더 이벤트를 출력 MHTML에 렌더링합니다. 다음 코드 스니펫은 MHTML로 변환하면서 캘린더 이벤트를 렌더링하는 방법을 보여줍니다:
from aspose.email import MailMessage, MhtSaveOptions, MhtFormatOptions, MhtTemplateName, MailMessageSaveType, FileCompatibilityMode
file_name = "message.msg"
# Load the MSG file
msg = MailMessage.load(data_dir + file_name)
# Create MHT save options
options = MhtSaveOptions()
options.mht_format_options = MhtFormatOptions.WRITE_HEADER | MhtFormatOptions.RENDER_CALENDAR_EVENT
# Save the message as MHTML
msg.save(data_dir + "Meeting with Recurring Occurrences.mhtml", options)
인라인 이미지 없이 이메일을 MHT로 내보내기
from aspose.email import MailMessage, MhtSaveOptions, MhtFormatOptions, MhtTemplateName, MailMessageSaveType, FileCompatibilityMode
# Load the EML file
eml = MailMessage.load(data_dir + "message.eml")
# Create MHT save options
mht_save_options = MhtSaveOptions()
mht_save_options.skip_inline_images = True
# Save the message as MHTML without inline images
eml.save(data_dir + "EmlToMhtmlWithoutInlineImages_out.mht", mht_save_options)
사용자 정의 시간대로 이메일을 MHT로 내보내기
MailMessage class는 다음을 제공합니다 TimeZoneOffset MHT로 내보내는 동안 사용자 정의 시간대를 설정하는 속성. 다음 코드 스니펫은 사용자 정의 시간대로 이메일을 MHT로 내보내는 방법을 보여줍니다:
from aspose.email import MailMessage, MhtSaveOptions, MhtFormatOptions, MhtTemplateName, MailMessageSaveType, FileCompatibilityMode
from datetime import timedelta
# Load the EML file
eml = MailMessage.load(data_dir + "message.eml")
# Set the local time for message date
eml.time_zone_offset = timedelta(hours=-8)
# The dates will be rendered by the local system time zone
mht_save_options = MhtSaveOptions()
mht_save_options.mht_format_options = MhtFormatOptions.WRITE_HEADER
eml.save(data_dir + "ExportEmailToMHTWithCustomTimezone_out.mhtml", mht_save_options)
HTML로 저장
다음은 HtmlSaveOptions class를 사용하면 메시지 본문을 HTML로 내보내고 내장 리소스를 저장하는 옵션을 제공받을 수 있습니다. 다음 코드 스니펫은 embed_resources 기본값이 true인 상태에서 메시지를 HTML로 저장하는 방법을 보여줍니다.
from aspose.email import MailMessage, SaveOptions, HtmlSaveOptions, HtmlFormatOptions
# Load the EML file
message = MailMessage.load(data_dir + "message.eml")
# Save the Email message as HTML
message.save(data_dir + "SaveAsHTML_out.html", SaveOptions.default_html)
# OR
eml = MailMessage.load(data_dir + "message.eml")
options = HtmlSaveOptions()
options.embed_resources = False
options.html_format_options = (
HtmlFormatOptions.WRITE_HEADER
| HtmlFormatOptions.WRITE_COMPLETE_EMAIL_ADDRESS
) # save the message headers to output HTML using the formatting options
eml.save(data_dir + "SaveAsHTML1_out.html", options)
Outlook 템플릿(.OFT)으로 저장
다음 코드 스니펫은 메시지를 Outlook 템플릿(.oft) 파일로 저장하는 방법을 보여줍니다.
from aspose.email import MailMessage, SaveOptions
eml = MailMessage("test@from.to", "test@to.to", "template subject", "Template body")
oft_eml_file_name = "EmlAsOft_out.oft"
options = SaveOptions.default_msg_unicode
options.save_as_template = True
eml.save(data_dir + oft_eml_file_name, options)