Lavorare con le proprietà MAPI
Determina il tipo di elemento MAPI in una cartella PST
Un file PST tipicamente contiene vari tipi di dati, come messaggi email, eventi di calendario, contatti e altro. Il MapiItemType La classe di Aspose.Email consente di accedere e categorizzare diversi tipi di elementi MAPI all’interno di un file PST. Il codice qui sotto dimostra come determinare il tipo di un elemento MAPI in una cartella PST:
import aspose.email as ae
import aspose.pycore as pycore
pst = ae.storage.pst.PersonalStorage.from_file("test.pst")
folder = pst.root_folder.get_sub_folder("Calendar")
for message_info in folder.enumerate_messages():
msg = pst.extract_message(message_info)
# Get the class type based on msg.supported_type
item_type = msg.supported_type
# Non-supported type. It cannot be accessed as appropriate item type.
if item_type == ae.mapi.MapiItemType.NONE:
print("Item type not supported")
# An email message.
elif item_type == ae.mapi.MapiItemType.MESSAGE:
# You can access to MapiMessage properties there.
# A subject for example
print(msg.subject)
# A contact item. Can be accessed as MapiContact.
elif item_type == ae.mapi.MapiItemType.CONTACT:
contact = pycore.cast(ae.mapi.MapiContact, msg.to_mapi_message_item())
# You can access to MapiContact properties there.
# A name_info.display_name for example.
print(contact.name_info.display_name)
# A calendar item. Can be accessed as MapiCalendar.
elif item_type == ae.mapi.MapiItemType.CALENDAR:
calendar = pycore.cast(ae.mapi.MapiCalendar, msg.to_mapi_message_item())
# You can access to MapiCalendar properties there.
# A location for example.
print(calendar.location)
# A distribution list. Can be accessed as MapiDistributionList.
elif item_type == ae.mapi.MapiItemType.DIST_LIST:
dlist = pycore.cast(ae.mapi.MapiDistributionList, msg.to_mapi_message_item())
# You can access to MapiDistributionList properties there
# A Journal entry. Can be accessed as MapiJournal.
elif item_type == ae.mapi.MapiItemType.JOURNAL:
journal = pycore.cast(ae.mapi.MapiJournal, msg.to_mapi_message_item())
# You can access to MapiJournal properties there
# A StickyNote. Can be accessed as MapiNote.
elif item_type == ae.mapi.MapiItemType.NOTE:
note = pycore.cast(ae.mapi.MapiNote, msg.to_mapi_message_item())
# You can access to MapiNote properties there
# A Task item. Can be accessed as MapiTask.
elif item_type == ae.mapi.MapiItemType.TASK:
task = pycore.cast(ae.mapi.MapiTask, msg.to_mapi_message_item())
# You can access to MapiTask properties there
Accedi e gestisci le proprietà MAPI
Il MapiProperty la classe rappresenta una proprietà MAPI, che contiene:
- Nome: una stringa che rappresenta il nome della proprietà.
- Tag: un intero lungo che rappresenta il tag della proprietà.
- Dati: un array di byte che rappresenta i dati della proprietà.
Ottieni proprietà MAPI usando il tag della proprietà
L’esempio di codice qui sotto carica un messaggio MAPI, recupera proprietà chiave come l’oggetto e la pagina di codice internet, e gestisce in modo sicuro l’eventuale assenza di queste proprietà. Per ottenere le proprietà MAPI:
- Carica il messaggio MAPI da un file usando il carica metodo.
- Usa il MapiPropertyTag classe per accedere a proprietà specifiche da un messaggio MAPI, come oggetto e pagina di codice internet.
- Gestisci proprietà mancanti.
from aspose.email.mapi import MapiMessage, MapiPropertyTag
# Load from file
msg = MapiMessage.load("message.msg")
# Access the MapiPropertyTag.PR_SUBJECT property
prop = msg.properties[MapiPropertyTag.SUBJECT]
# If the property is not found, check the MapiPropertyTag.PR_SUBJECT_W (which is a // Unicode peer of the MapiPropertyTag.PR_SUBJECT)
if prop is None:
prop = msg.properties[MapiPropertyTag.SUBJECT_W]
# Cannot found
if prop is None:
print("No property found!")
# Get the property data as string
subject = prop.get_string()
print("Subject:" + subject)
# Read internet code page property
prop = msg.properties[MapiPropertyTag.INTERNET_CPID]
if prop is not None:
print("CodePage:" + str(prop.get_long()))
Imposta le proprietà MAPI
Il seguente frammento di codice mostra come impostare le proprietà MAPI.
Leggere proprietà MAPI nominate
Aspose.Email fornisce un insieme di API per lavorare con i file MSG, inclusa l’estrazione delle proprietà MAPI nominate.
Leggere proprietà MAPI nominate dai file MSG
Per leggere le proprietà MAPI nominate, è possibile utilizzare il named_properties proprietà del MapiMessage classe. Il seguente esempio di codice mostra come caricare un messaggio, recuperare tutte le proprietà MAPI nominate, iterare su ogni proprietà per verificarne il valore:
import aspose.email as ae
msg = ae.mapi.MapiMessage.load("my.msg")
# Get all named MAPI properties
properties = msg.named_properties.values
# Read all properties in foreach loop
for prop in properties:
# Read any specific property
if prop.descriptor.canonical_name == "PidLidSideEffects":
print(f"{prop.descriptor.canonical_name} = {prop}")
if prop.descriptor.canonical_name == "PidLidInternetAccountName":
print(f"{prop.descriptor.canonical_name} = {prop}")
Leggere proprietà MAPI nominate dagli allegati
Aspose.Email rende possibile recuperare tutte le proprietà MAPI nominate di un allegato. Il seguente esempio di codice mostra come leggere le proprietà MAPI nominate dagli allegati:
import aspose.email as ae
msg = ae.mapi.MapiMessage.load("my.msg")
# Get all named MAPI properties
attach_properties = msg.attachments[0].named_properties.values
# Read all properties in foreach loop
for prop in attach_properties:
# Read any specific property
if prop.descriptor.name == "AttachmentOriginalUrl":
print(f"{prop.descriptor.name} = {prop.get_string()}")
if prop.descriptor.name == "AttachmentWasSavedToCloud":
print(f"{prop.descriptor.name} = {prop.get_boolean()}")
Gestione delle proprietà
Rimuovere proprietà da file MSG e allegati
Il seguente esempio di codice dimostra la creazione di un messaggio Outlook MSG con contenuto del corpo e un file di messaggio allegato. Mostra anche come eliminare una proprietà di allegato dal messaggio creato.
import aspose.email as ae
# create an MSG
msg = ae.mapi.MapiMessage("from@domain.com", "to@domain.com", "subject", "body")
msg.set_body_content("<html><body><h1>This is the body content</h1></body></html>", ae.mapi.BodyContentType.HTML)
# load message and add it to created MSG as attachment
attachment = ae.mapi.MapiMessage.load("attach.msg")
msg.attachments.add("Outlook2 Test subject.msg", attachment)
# count of attachment properties before removal
print(f"Before removal = {msg.attachments[0].properties.count}")
# Delete anyone attachment property
msg.attachments[0].remove_property(923467779)
# count of attachment properties after removal
print(f"After removal = {msg.attachments[0].properties.count}")
Convertire MSG in messaggio MIME
L’API Aspose.Email offre la possibilità di convertire un file MSG in un messaggio MIME utilizzando il to_mail_message metodo.
Impostare il timeout per la conversione e il caricamento dei messaggi
Per limitare il tempo in millisecondi della conversione del messaggio (valore predefinito 3 sec), la proprietà timeout del MailConversionOptions viene utilizzata la classe.
Ecco come è possibile impostare un timeout per i processi di conversione e caricamento dei messaggi:
import aspose.email as ae
msg = ae.mapi.MapiMessage.load("my.msg")
options = ae.mapi.MailConversionOptions()
options.timeout = 5000
mailMessage = msg.to_mail_message(options)
Impostando un timeout per i processi di conversione e caricamento dei messaggi, è possibile controllare il tempo massimo consentito a queste operazioni. Dopo aver impostato il timeout, è possibile procedere con le operazioni di conversione e caricamento del messaggio.
Impostare la categoria colore per file Outlook MSG
A volte potrebbe essere necessario differenziare le email di particolare importanza e organizzarle visivamente. La libreria fornisce un modo per farlo assegnando un colore specifico a un elemento di messaggio. Quando imposti una categoria colore per un elemento, ti consente di identificare e individuare facilmente gli elementi correlati a colpo d’occhio. Usa FollowUpManager classe per impostare la categoria colore per un messaggio come mostrato nel seguente esempio di codice:
import aspose.email as ae
msg = ae.mapi.MapiMessage.load("my.msg")
# Add Two categories
ae.mapi.FollowUpManager.add_category(msg, "Purple Category")
ae.mapi.FollowUpManager.add_category(msg, "Red Category")
# Retrieve the list of available categories
categories = ae.mapi.FollowUpManager.get_categories(msg)
# Remove the specified category and then Clear all categories
ae.mapi.FollowUpManager.remove_category(msg, "Red Category")
ae.mapi.FollowUpManager.clear_categories(msg)