Laddning, sparning och konvertering av e‑post
Upptäcka e-postfilformat
Aspose.Email API tillhandahåller möjligheten att upptäcka filformatet för den angivna meddelandefilen. Den DetectFileFormat metod för FileFormatUtil Klassen kan användas för att uppnå detta. Följande klasser och metoder kan användas för att upptäcka det laddade filformatet:
- Enum FileFormatType
- Klass FileFormatInfo
- Klass FileFormatUtil
- Metod detect_file_format(ström)
- Metod detect_file_format(file_path)
Följande kodsnutt visar hur du upptäcker filformat:
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))
Läsa ett meddelande med inläsningsalternativ
Följande kodsnutt visar hur du läser ett meddelande med inläsningsalternativ.
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)
Bevara inbäddat meddelandeformat vid inläsning
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))
Spara och konvertera e‑post
Aspose.Email underlättar att konvertera vilken meddelandetyp som helst till ett annat format. För att demonstrera denna funktion laddar koden i denna artikel tre typer av meddelanden från disk och sparar dem tillbaka i andra format. Bas‑klassen SaveOptions och klasserna EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions kan användas för ytterligare inställningar när meddelanden sparas till andra format. Artikeln visar hur du använder dessa klasser för att spara ett exempelmail som:
- EML-format.
- Outlook MSG.
- MHTML-format.
- HTML-format.
Spara som EML
Följande kodsnutt visar hur du läser ett EML‑meddelande och sparar det på disken i samma format.
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)
Bevara gränser i EML‑filer
Följande kodsnutt visar hur du läser en EML‑fil och sparar den i samma format med bevarande av de ursprungliga gränserna.
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)
Anpassa MIME‑gränsträngar
Aspose.Email för .NET låter dig konfigurera gränsmallen som används i MIME‑meddelanden. Detta uppnås via boundaries_template egenskap hos EmlSaveOptions klass.
Genom att ange en anpassad mall kan du definiera hur MIME‑gränser genereras. Jokertecknet {#} i mallen ersätts med ett inkrementellt gränsnummer, vilket möjliggör dynamiska och läsbara gränsträngar.
Om boundaries_template är inte inställd (standard är None), så använder biblioteket sitt interna gränsformat.
Följande kodexempel visar hur du anpassar MIME‑gränsträngarna när du sparar ett e‑postmeddelande i .eml‑format:
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)
Här är ett exempel på meddelandestrukturen med anpassade gränser sparade med koden ovan:
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--
Bevara TNEF‑bilagor i EML‑filer
Följande kodsnutt visar hur du sparar en EML‑fil med bevarande av TNEF‑bilagor.
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)
Spara som MSG
Följande kodsnutt visar hur du läser ett EML‑meddelande och konverterar det till MSG med det lämpliga alternativet från 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)
Bevara datum i MSG‑filer
Den MsgSaveOptions klass låter dig spara ursprungsmeddelandet som en Outlook‑meddelandefil (MSG) med bevarande av datum. Följande kodsnutt visar hur du sparar en EML‑fil som MSG och bevarar datum.
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)
Spara som MHTML
Olika MHTML‑alternativ kan användas för att uppnå önskat resultat. Följande kodsnutt visar hur du laddar ett EML‑meddelande i MailMessage och konvertera det till 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)
Anpassade MHTML‑konverteringsinställningar
Den MhtSaveOptions klass erbjuder ytterligare alternativ för att spara e‑postmeddelanden i MHTML-format. Enumerationen MhtFormatOptions gör det möjligt att skriva ytterligare e‑postinformation till MHTML-utdata. Följande extra fält kan skrivas:
- NONE - Inga specifika inställningar angivna.
- WRITE_HEADER - Anger att huvudinformation ska skrivas.
- WRITE_OUTLINE_ATTACHMENTS - Anger att outline‑bilagor ska skrivas.
- WRITE_COMPLETE_EMAIL_ADDRESS - Anger att fullständig e‑postadress ska skrivas i alla e‑posthuvuden.
- NO_ENCODE_CHARACTERS - Anger att ingen teckenkodning ska användas.
- HIDE_EXTRA_PRINT_HEADER - Anger att PageHeader kommer att vara osynlig.
- WRITE_COMPLETE_TO_EMAIL_ADDRESS - Anger att fullständig e‑postadress ska skrivas i ‘To’-huvudet.
- WRITE_COMPLETE_FROM_EMAIL_ADDRESS - Anger att fullständig e‑postadress ska skrivas i ‘From’-huvudet.
- WRITE_COMPLETE_CC_EMAIL_ADDRESS - Anger att fullständig e‑postadress ska skrivas i ‘Cc’-huvudet.
- WRITE_COMPLETE_BCC_EMAIL_ADDRESS - Anger att fullständig e‑postadress ska skrivas i ‘Bcc’-huvudet.
- RENDER_CALENDAR_EVENT - Anger att text från kalenderhändelse ska skrivas i utdata‑mhtml.
- SKIP_BYTE_ORDER_MARK_IN_BODY - Anger att Byte Order Mark (BOM)-byte ska skrivas till kroppen.
- RENDER_V_CARD_INFO - Anger att text från VCard AlternativeView ska skrivas i utdata‑mhtml.
- DISPLAY_AS_OUTLOOK - Anger att From‑huvudet ska visas som i Outlook.
- RENDER_TASK_FIELDS - Anger att specifika Task‑fält ska skrivas i utdata‑mhtml.
Följande kodsnutt visar hur du konverterar en EML‑fil till MHTML med valfria inställningar.
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)
Inkludera kalenderhändelser i MHTML‑konvertering
Den MhtFormatOptions.RenderCalendarEvent renderar kalenderhändelser till utdata‑MHTML. Följande kodsnutt visar hur du renderar kalenderhändelser vid konvertering till 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)
Exportera e‑post till MHT utan inbäddade bilder
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)
Exportera e‑post till MHT med anpassad tidszon
MailMessage klass tillhandahåller TimeZoneOffset egenskap för att ange anpassad tidszon vid export till MHT. Följande kodsnutt visar hur du exporterar ett e‑postmeddelande till MHT med anpassad tidszon:
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)
Spara som HTML
Den HtmlSaveOptions klass låter dig exportera meddelandekroppen till HTML med möjlighet att spara inbäddade resurser. Följande kodsnutt visar hur du sparar ett meddelande som HTML där standardvärdet för embed_resources är true.
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)
Spara som Outlook‑mall (.OFT)
Följande kodsnutt visar hur du sparar ett meddelande som en Outlook‑mall (.oft)-fil.
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)