Gestione dei contatti Outlook nei file PST

Creazione, salvataggio e lettura di contatti

Aspose.Email consente di creare e gestire contatti Outlook. Il MapiContact la classe fornisce tutte le proprietà correlate ai contatti necessarie per creare e manipolare un contatto Outlook. Questo articolo mostra come creare, salvare e leggere un contatto Outlook usando il MapiContact classe.

Crea e salva contatti Outlook

Per creare un contatto e salvarlo su disco, segui questi passaggi:

  1. Istanzia un nuovo oggetto della MapiContact classe.
  2. Inserisci le informazioni delle proprietà del contatto.
  3. Aggiungi dati foto (se presenti).
  4. Salva il contatto in formato MSG o VCard.

Il seguente frammento di codice mostra come creare e salvare un contatto Outlook:

import aspose.email as ae

data_dir = "path/to/data/directory/"

contact = ae.mapi.MapiContact()
contact.name_info = ae.mapi.MapiContactNamePropertySet("Bertha", "A.", "Buell")
contact.professional_info = ae.mapi.MapiContactProfessionalPropertySet("Awthentikz", "Social work assistant")
contact.personal_info.personal_home_page = "B2BTies.com"
contact.physical_addresses.work_address.address = "Im Astenfeld 59 8580 EDELSCHROTT"
contact.electronic_addresses.email1 = ae.mapi.MapiContactElectronicAddress("Experwas", "SMTP", "BerthaABuell@armyspy.com")
contact.telephones = ae.mapi.MapiContactTelephonePropertySet("06605045265")
contact.personal_info.children = ["child1", "child2", "child3"]
contact.categories = ["category1", "category2", "category3"]
contact.mileage = "Some test mileage"
contact.billing = "Test billing information"
contact.other_fields.journal = True
contact.other_fields.private = True
contact.other_fields.reminder_topic = "Test topic"
contact.other_fields.user_field1 = "ContactUserField1"
contact.other_fields.user_field2 = "ContactUserField2"
contact.other_fields.user_field3 = "ContactUserField3"
contact.other_fields.user_field4 = "ContactUserField4"

# Add a photo
with open(data_dir + "Desert.jpg", "rb") as file:
    buffer = file.read()
    contact.photo = ae.mapi.MapiContactPhoto(buffer, ae.mapi.MapiContactPhotoImageFormat.JPEG)

# Save the Contact in MSG format
contact.save(data_dir + "MapiContact_out.msg", ae.mapi.ContactSaveFormat.MSG)

# Save the Contact in VCF format
contact.save(data_dir + "MapiContact_out.vcf", ae.mapi.ContactSaveFormat.V_CARD)

Salva contatti in formato VCF Versione 3

Per salvare un contatto in formato VCF Versione 3, usa la proprietà version del VCardSaveOptions classe.

  1. Crea una nuova istanza della VCardSaveOptions classe.
  2. Imposta la proprietà version dell’oggetto VCardSaveOptions a VCardVersion.V30. Questo imposta la versione vCard a 3.0.
  3. Chiama il salva metodo dell’oggetto MapiContact, passando il nome file "contact.vcf" e l’oggetto VCardSaveOptions come parametri. Questo salva il contatto come file vCard con il nome file e le opzioni specificate.

Il seguente frammento di codice mostra come salvare un contatto in formato VCF Versione 3:

import aspose.email as ae

contact = ae.mapi.MapiContact()
contact.name_info = ae.mapi.MapiContactNamePropertySet("Bertha", "A.", "Buell")
options = ae.personalinfo.vcard.VCardSaveOptions()
options.version = ae.personalinfo.vcard.VCardVersion.V30
contact.save("contact.vcf", options)

Carica contatti da file MSG o VCard

Il MapiContact la classe può essere usata per caricare contatti sia in formato Outlook MSG che VCard.

Per caricare un contatto da MSG, usa il campione di codice qui sotto:

import aspose.pycore as pycore
from aspose.email.mapi import MapiMessage, MapiContact

message = MapiMessage.load(data_dir + "contact.msg")
contact = pycore.cast(MapiContact, message.to_mapi_message_item())

print(contact.name_info.display_name)
print(contact.electronic_addresses.email1.email_address)

Per caricare un contatto da VCard, usa il seguente campione di codice:

from aspose.email.mapi import MapiContact
from aspose.email.personalinfo.vcard import VCardContact

# Load the vCard into a VCardContact object
vcard_contact = VCardContact.load(data_dir + "contact.vcf")
print(vcard_contact.identification_info.display_name)

# Or load it directly into a MapiContact object
mapi_contact = MapiContact.from_v_card(data_dir + "contact.vcf")
print(mapi_contact.name_info.display_name)

Carica contatti MAPI da vCard con opzioni personalizzate

Per fornire maggiore flessibilità nella conversione di file vCard (.vcf) in contatti MAPI, Aspose.Email offre una sovraccarico del MapiContact.from_v_card metodo che accetta un VCardLoadOptions oggetto. Offre un controllo migliorato su come i file vCard vengono interpretati — soprattutto quando si lavora con formati vCard diversi, codifiche o scenari di parsing avanzati.

Il contatto caricato può quindi essere usato all’interno di file PST, esportato in MSG o convertito in altri formati compatibili con Outlook.

from aspose.email.mapi import MapiContact
from aspose.email.personalinfo.vcard import VCardLoadOptions

mapi_contact = MapiContact.from_v_card("contact.vcf", VCardLoadOptions())
print(mapi_contact.name_info.display_name)

Carica contatti con codifica specificata

Il seguente frammento di codice mostra come caricare un contatto da vcard con codifica specificata.

from aspose.email.mapi import MapiContact

contact = MapiContact.from_v_card(data_dir + "contact.vcf", "UTF-8")

print(contact.name_info.display_name)

Salva file VCard con codifica dei caratteri personalizzata

Quando salvi un file VCard, puoi definire la codifica dei caratteri per garantire la compatibilità con caratteri non ASCII. Ad esempio, impostando la proprietà preferred_text_encoding del VCardSaveOptions impostare l’oggetto a "utf-8" garantisce la corretta codifica del testo non ASCII. Questa funzionalità è particolarmente utile per gestire dati di contatto multilingua. Di seguito è un esempio di come configurare e salvare un file vCard con codifica dei caratteri personalizzata:

import aspose.email as ae

contact = ae.mapi.MapiContact()
contact.name_info = ae.mapi.MapiContactNamePropertySet("Bertha", "A.", "Buell")
options = ae.personalinfo.vcard.VCardSaveOptions()
options.preferred_text_encoding = "utf-8"
contact.save("contact.vcf", options)

Salva file VCard con proprietà estese

Oltre ai campi standard vCard, puoi migliorare i tuoi file vCard includendo proprietà estese. Questi sono attributi aggiuntivi non coperti dalla specifica vCard standard, consentendo una maggiore personalizzazione. Per abilitarlo, imposta la proprietà use_extensions del VCardSaveOptions classe a True. Questo è particolarmente utile per aggiungere metadati personalizzati o specifici dell’applicazione. Ecco come puoi salvare un file vCard con le proprietà estese abilitate:

import aspose.email as ae

contact = ae.mapi.MapiContact()
contact.name_info = ae.mapi.MapiContactNamePropertySet("Bertha", "A.", "Buell")
options = ae.personalinfo.vcard.VCardSaveOptions()
options.use_extensions = True
contact.save("contact.vcf", options)

Leggi più contatti in formato VCard

Per recuperare tutti i contatti da un VCard, puoi usare il seguente metodi:

  • is_multi_contacts determina se uno stream contiene più contatti.
  • load_as_multiple(file_path) carica un elenco di tutti i contatti da un file VCard.
  • load_as_multiple(stream) carica un elenco di tutti i contatti da uno stream VCard.

Il frammento di codice qui sotto dimostra il processo di lettura di più contatti da un file VCard:

import aspose.email as ae

contact = ae.mapi.MapiContact()
contact.name_info = ae.mapi.MapiContactNamePropertySet("Bertha", "A.", "Buell")
options = ae.personalinfo.vcard.VCardSaveOptions()
options.use_extensions = True
contact.save("contact.vcf", options)

if ae.personalinfo.vcard.VCardContact.is_multi_contacts("contact.vcf"):
    ae.personalinfo.vcard.VCardContact.load_as_multiple("contact.vcf")

Leggi e Imposta l’Identificatore del Prodotto di un Contatto

Un file vCard registra il prodotto che lo ha creato nel PRODID campo. Aspose.Email conserva questo identificatore quando un contatto è convertito tra vCard e MSG, così è possibile tracciare sempre la sorgente del contatto. L’identificatore è disponibile tramite le seguenti proprietà:

Il seguente esempio di codice legge l’identificatore prodotto da un file vCard, converte il contatto in MSG e lo salva con un nuovo identificatore:

import io
import aspose.email as ae
from aspose.pycore import cast

# Read the product identifier from a vCard file
vcard = ae.personalinfo.vcard.VCardContact.load("contact.vcf")
print("vCard product ID:", vcard.explanatory_info.prod_id)

# The identifier is kept when the contact is converted to MSG
msg_stream = io.BytesIO()
vcard.save(msg_stream, ae.mapi.ContactSaveFormat.MSG)
msg_stream.seek(0)
msg = ae.mapi.MapiMessage.load(msg_stream)

if msg.supported_type == ae.mapi.MapiItemType.CONTACT:
    contact = cast(ae.mapi.MapiContact, msg.to_mapi_message_item())
    print("MapiContact product ID:", contact.product_id)

    # Save the contact to MSG with a different product identifier
    options = ae.mapi.MapiContactSaveOptions()
    options.product_id = "-//Contoso//Address Book 2.0//EN"
    contact.save("contact_out.msg", options)

Per impostare l’identificatore per un nuovo contatto, assegna il product_id proprietà o passa l’identificatore attraverso VCardSaveOptions quando si salva il contatto come vCard:

import aspose.email as ae

contact = ae.mapi.MapiContact("John Smith", "john.smith@example.com")
contact.product_id = "-//Contoso//Address Book 2.0//EN"
contact.save("contact_out.vcf", ae.mapi.ContactSaveFormat.V_CARD)

# Override the identifier for a single save operation
options = ae.personalinfo.vcard.VCardSaveOptions()
options.product_id = "-//Contoso//Export Tool 1.0//EN"
contact.save("contact_export.vcf", options)

Liste di distribuzione e file VCF

Salva liste di distribuzione MAPI in file VCF

Un MapiDistributionList può essere scritto come un file VCF multi-contatto. Passa un MapiDistributionListSaveOptions oggetto creato con ContactSaveFormat.V_CARD al save metodo:

from aspose.email.mapi import (MapiDistributionList, MapiDistributionListMember,
                               MapiDistributionListMemberCollection,
                               MapiDistributionListSaveOptions, ContactSaveFormat)

members = MapiDistributionListMemberCollection()
members.append(MapiDistributionListMember("Sebastian Wright", "SebastianWright@dayrep.com"))
members.append(MapiDistributionListMember("Wichert Kroos", "WichertKroos@teleworm.us"))

dlist = MapiDistributionList("Contact List", members)

options = MapiDistributionListSaveOptions(ContactSaveFormat.V_CARD)
dlist.save("distribution_list.vcf", options)

Lo stesso vale per una lista di distribuzione letta da un file MSG — converti il messaggio caricato con to_mapi_message_item() primo.

Converti file VCF multi-contatto in MapiDistributionList

Aspose.Email supporta la conversione di file VCF multipli in MapiDistributionList oggetti, il che rende facile gestire e importare più contatti direttamente nelle tue applicazioni. La funzionalità è disponibile tramite il metodo statico MapiDistributionList.from_vcf metodo, che accetta sia un percorso file sia uno stream:

from aspose.email.mapi import MapiDistributionList

# Convert a multi-contact VCF file to a MapiDistributionList
dlist = MapiDistributionList.from_vcf("distribution_list.vcf")

print(dlist.display_name)
for member in dlist.members:
    print(f"{member.display_name}: {member.email_address}")

Rendi informazioni del contatto in MHTML

Il contatto Outlook può essere convertito in MHTML usando l’API Aspose.Email. Il seguente campione di codice dimostra come generare un file MHTML che contiene informazioni dettagliate sul contatto originariamente da un file MSG:

  1. Carica il file MSG come un MapiMessage oggetto.
  2. Converti il messaggio in formato EML.
  3. Prepara le opzioni di salvataggio MHT:
    • Abilita la codifica del contenuto del corpo e preserva i limiti originali.
    • Imposta le opzioni del formato MHT per scrivere intestazioni e rendere le informazioni vCard.
  4. Definisci i campi da rendere nel MHT.
  5. Salva l’EML come file MHTML.
import aspose.email as ae
from aspose.email.mapi import MapiMessage, MailConversionOptions

msg = MapiMessage.load(data_dir + "contact.msg")
eml = msg.to_mail_message(MailConversionOptions())

# Prepare the MHT format options
mht_save_options = ae.MhtSaveOptions()
mht_save_options.check_body_content_encoding = True
mht_save_options.preserve_original_boundaries = True
mht_save_options.mht_format_options = (ae.MhtFormatOptions.WRITE_HEADER |
                                       ae.MhtFormatOptions.RENDER_V_CARD_INFO)
mht_save_options.rendered_contact_fields = (ae.ContactFieldsSet.NAME_INFO |
                                            ae.ContactFieldsSet.PERSONAL_INFO |
                                            ae.ContactFieldsSet.TELEPHONES |
                                            ae.ContactFieldsSet.EVENTS)

eml.save(data_dir + "RenderingContactInformationToMhtml_out.mhtml", mht_save_options)