Introduzione
Aspose.Email FOSS for Python goes beyond basic message creation. The library exposes the full depth of the MAPI property model, letting you read, write, and query individual properties by ID and type. It handles recipients, attachments, and embedded messages as first-class objects, and provides bidirectional conversion between the MSG binary format and Python’s standard email.message.EmailMessage.
A livello di contenitore, il lettore e lo scrittore CFB ti offrono un controllo deterministico sui documenti Compound File Binary. Puoi attraversare le gerarchie di storage, estrarre dati di flusso grezzi, creare nuovi contenitori da zero e serializzarli nuovamente in byte. Entrambi CFBError e MsgError forniscono la gestione strutturata delle eccezioni per input malformato.
Questo post illustra ogni funzionalità con esempi di codice verificati, tratti direttamente dalla suite di test della libreria e dagli script di esempio.
Cosa è incluso
Accesso alle proprietà MAPI
Ogni file MSG è costruito su proprietà MAPI. MapiMessage espone set_property() e get_property() per lavorare con le proprietà tramite il loro PropertyId valore enum. Usa iter_properties() per enumerare tutte le proprietà di un messaggio, o get_property_value() per il recupero diretto del valore con decodifica opzionale del tipo.
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")
Per leggere le proprietà da un file esistente:
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}")
Destinatari e allegati
Aggiungi destinatari con add_recipient(), specificando il nome visualizzato e il tipo di destinatario (To, CC, or BCC). Allega file con add_attachment() usando byte grezzi e un tipo MIME. Per i messaggi nidificati, add_embedded_message_attachment() incorpora un completo MapiMessage come oggetto figlio all’interno del genitore.
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")
Per ispezionare gli allegati di un messaggio esistente:
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}")
Conversione da MSG a EmailMessage
La libreria converte in entrambe le direzioni tra MSG e Python’s email.message.EmailMessage. Usa to_email_message() per produrre un oggetto MIME conforme agli standard, o from_email_message() per importare un esistente EmailMessage nel formato MSG. Metodi di comodità to_email_bytes() e to_email_string() serializza direttamente in byte o testo.
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]}")
Round-trip del contenitore CFB
Crea e serializza contenitori Compound File Binary in modo indipendente dallo strato MSG. CFBDocument.from_file() carica un contenitore esistente in un modello di documento mutabile con CFBStorage e CFBStream nodi. CFBWriter.write_file() serializza il documento nuovamente su disco in modo deterministico.
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")
Gestione degli errori
La libreria solleva CFBError per contenuto CFB malformato e MsgError per struttura MSG non valida. MapiMessage espone anche una property validation_issues che restituisce una tupla di stringhe di avviso senza sollevare un’eccezione, lasciandoti decidere quanto rigorosamente gestire i file non conformi.
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}")
Avvio rapido
pip install aspose-email-foss>=26.3
Carica un MSG esistente, leggi i suoi metadati e elenca gli allegati:
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}")
Formati supportati
| Formato | Importa | Esporta |
|---|---|---|
| MSG | Sì | Sì |
| CFB | Sì | Sì |
Open Source e Licenze
Aspose.Email FOSS for Python is released under the MIT License. Puoi usarlo in progetti personali, interni e commerciali senza restrizioni. Il codice sorgente è disponibile su GitHub.