Créer, enregistrer et charger des contacts Outlook en C++
Aspose.Email pour C++ vous permet de créer et gérer des contacts Microsoft Outlook de façon programmatique. Le MapiContact la classe fournit toutes les propriétés liées aux contacts, y compris les noms, les informations professionnelles, les adresses, les comptes e‑mail, les numéros de téléphone, les catégories, les champs personnalisés et les photos.
Cet article montre comment créer, enregistrer et lire des contacts Outlook aux formats MSG et vCard (VCF).
Les exemples de cet article utilisent ces en‑têtes et espaces de noms :
#include <MailMessage.h>
#include <SaveOptions.h>
#include <MhtSaveOptions.h>
#include <MhtFormatOptions.h>
#include <MsgLoadOptions.h>
#include <ContactFieldsSet.h>
#include <Mapi/MapiContact.h>
#include <Mapi/MapiContactNamePropertySet.h>
#include <Mapi/MapiContactProfessionalPropertySet.h>
#include <Mapi/MapiContactPersonalInfoPropertySet.h>
#include <Mapi/MapiContactPhysicalAddressPropertySet.h>
#include <Mapi/MapiContactPhysicalAddress.h>
#include <Mapi/MapiContactElectronicAddressPropertySet.h>
#include <Mapi/MapiContactElectronicAddress.h>
#include <Mapi/MapiContactTelephonePropertySet.h>
#include <Mapi/MapiContactOtherPropertySet.h>
#include <Mapi/MapiContactPhoto.h>
#include <Mapi/MapiContactPhotoImageFormat.h>
#include <Mapi/MapiItemType.h>
#include <Mapi/MapiDistributionList.h>
#include <Mapi/MapiDistributionListSaveOptions.h>
#include <Mapi/MapiDistributionListMemberCollection.h>
#include <Mapi/ContactSaveFormat.h>
#include <Mapi/MapiMessage.h>
#include <Mapi/MailConversionOptions.h>
#include <PersonalInfo/vCard/VCardContact.h>
#include <PersonalInfo/vCard/VCardIdentificationInfo.h>
#include <PersonalInfo/vCard/VCardLoadOptions.h>
#include <PersonalInfo/vCard/VCardSaveOptions.h>
#include <PersonalInfo/vCard/VCardVersion.h>
#include <system/io/memory_stream.h>
#include <system/text/encoding.h>
#include <system/array.h>
#include <system/convert.h>
#include <system/io/file.h>
using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Mapi;
using namespace Aspose::Email::PersonalInfo::VCard;
Créer et enregistrer un contact Outlook
Pour créer un contact Outlook et l’enregistrer sur le disque, suivez les étapes ci-dessous :
- Instancier MapiContact.
- Remplissez le nom, les informations professionnelles, personnelles et les détails d’adresse.
- Ajoutez des adresses électroniques et des numéros de téléphone.
- Attribuez des catégories, kilométrage, facturation et champs personnalisés.
- Optionnellement, intégrez une photo de contact.
- Enregistrez le contact au format MSG ou vCard (VCF).
Les détails d’un contact sont regroupés en ensembles de propriétés : MapiContactNamePropertySet pour le nom, MapiContactProfessionalPropertySet pour l’entreprise et le titre du poste, MapiContactPhysicalAddressPropertySet pour les adresses postales, MapiContactElectronicAddressPropertySet pour les adresses e‑mail et fax, MapiContactTelephonePropertySet pour les numéros de téléphone et MapiContactOtherPropertySet pour les champs restants tels que le rappel et les champs utilisateur. MapiContact::Save enregistre le contact en MSG ou en vCard, selon le ContactSaveFormat.
SharedPtr<MapiContact> contact = MakeObject<MapiContact>();
contact->set_NameInfo(MakeObject<MapiContactNamePropertySet>(u"Bertha", u"A.", u"Buell"));
contact->set_ProfessionalInfo(MakeObject<MapiContactProfessionalPropertySet>(u"Awthentikz", u"Social work assistant"));
contact->get_PersonalInfo()->set_PersonalHomePage(u"B2BTies.com");
contact->get_PhysicalAddresses()->get_WorkAddress()->set_Address(u"Im Astenfeld 59 8580 EDELSCHROTT");
contact->get_ElectronicAddresses()->set_Email1(MakeObject<MapiContactElectronicAddress>(u"Experwas", u"SMTP", u"BerthaABuell@armyspy.com"));
contact->set_Telephones(MakeObject<MapiContactTelephonePropertySet>(u"06605045265"));
contact->get_PersonalInfo()->set_Children(MakeArray<String>({u"child1", u"child2", u"child3"}));
contact->set_Categories(MakeArray<String>({u"category1", u"category2", u"category3"}));
contact->set_Mileage(u"Some test mileage");
contact->set_Billing(u"Test billing information");
contact->get_OtherFields()->set_Journal(true);
contact->get_OtherFields()->set_Private(true);
contact->get_OtherFields()->set_ReminderTime(DateTime(2014, 1, 1, 0, 0, 55));
contact->get_OtherFields()->set_ReminderTopic(u"Test topic");
contact->get_OtherFields()->set_UserField1(u"ContactUserField1");
contact->get_OtherFields()->set_UserField2(u"ContactUserField2");
// a photo is stored with the format of its data
contact->set_Photo(MakeObject<MapiContactPhoto>(IO::File::ReadAllBytes(u"portrait.jpg"), MapiContactPhotoImageFormat::Jpeg));
contact->Save(u"Contact_out.msg", ContactSaveFormat::Msg);
contact->Save(u"Contact_out.vcf", ContactSaveFormat::VCard);
Lire un contact avec MapiContact
Le MapiContact la classe peut charger des contacts Outlook enregistrés aux formats MSG et VCF.
Charger un contact depuis MSG
Un fichier MSG contenant un contact est chargé comme tout autre élément Outlook, avec MapiMessage::Load. ToMapiMessageItem puis renvoie l’élément en tant que MapiContact. Vérification get_SupportedType vérifie d’abord que le fichier contient réellement un contact – DynamicCast lance une exception lorsque l’élément est d’un autre type.
SharedPtr<MapiMessage> msg = MapiMessage::Load(u"Contact_out.msg");
if (msg->get_SupportedType() == MapiItemType::Contact)
{
SharedPtr<MapiContact> mapiContact = DynamicCast<MapiContact>(msg->ToMapiMessageItem());
Console::WriteLine(u"Name: " + mapiContact->get_NameInfo()->get_DisplayName());
Console::WriteLine(u"Company: " + mapiContact->get_ProfessionalInfo()->get_CompanyName());
Console::WriteLine(u"E-mail: " + mapiContact->get_ElectronicAddresses()->get_Email1()->get_EmailAddress());
}
Charger un contact à partir d’une vCard (VCF)
Un fichier vCard peut être lu de deux manières. VCardContact::Load donne un VCardContact qui reflète la structure de la vCard – le bon choix lorsque les données restent au format vCard (voir Travailler avec des fichiers vCard). MapiContact::FromVCard convertit la vCard directement en un contact Outlook, prêt à être enregistré en MSG ou ajouté à un fichier PST.
// the vCard object model
SharedPtr<VCardContact> vcard = VCardContact::Load(u"Contact_out.vcf");
Console::WriteLine(u"vCard display name: " + vcard->get_IdentificationInfo()->get_DisplayName());
// the same file as an Outlook contact
SharedPtr<MapiContact> contact = MapiContact::FromVCard(u"Contact_out.vcf");
Console::WriteLine(u"MapiContact display name: " + contact->get_NameInfo()->get_DisplayName());
Contrôler comment une vCard est lue et écrite
MapiContact::FromVCard possède des surcharges qui prennent un VCardLoadOptions objet ou un encodage, ce qui compte pour les fichiers écrits avec une page de code legacy. À la sortie, VCardSaveOptions choisit le version vCard et décide via UseExtensions si les extensions X- les propriétés peuvent être écrites – désactivez cette option lorsque l’application cible ne comprend que les champs standard.
// load a vCard with explicit options
SharedPtr<VCardLoadOptions> loadOptions = MakeObject<VCardLoadOptions>();
loadOptions->set_PreferredEncoding(System::Text::Encoding::get_UTF8());
SharedPtr<MapiContact> contact = MapiContact::FromVCard(u"Contact.vcf", loadOptions);
Console::WriteLine(contact->get_NameInfo()->get_DisplayName());
// write it back as vCard 3.0, without the extended X- properties
SharedPtr<VCardSaveOptions> saveOptions = MakeObject<VCardSaveOptions>();
saveOptions->set_Version(VCardVersion::V30);
saveOptions->set_UseExtensions(false);
contact->Save(u"ContactV3.vcf", saveOptions);
Listes de distribution et fichiers VCF multi‑contacts
Un fichier VCF contenant plusieurs contacts correspond à un MapiDistributionList: FromVCF lit un tel fichier, et classe comme paramètres. La avec ContactSaveFormat::VCard écrit un retour.
// a multi-contact VCF file becomes a distribution list
SharedPtr<MapiDistributionList> dlist = MapiDistributionList::FromVCF(u"contacts.vcf");
Console::WriteLine(u"Members: " + Convert::ToString(dlist->get_Members()->get_Count()));
// and a distribution list can be written back as a multi-contact VCF file
SharedPtr<MapiDistributionListSaveOptions> options = MakeObject<MapiDistributionListSaveOptions>(ContactSaveFormat::VCard);
options->set_Version(VCardVersion::V30);
dlist->Save(u"distribution_list.vcf", options);
Rendre un contact en MHTML
Une carte de contact peut être publiée au format MHTML – une page compatible e‑mail qui montre les champs comme le fait Outlook. Le contact est enregistré dans un flux MSG, relu comme un MapiMessage, converti en un MailMessage et enregistrés avec MhtFormatOptions::RenderVCardInfo. RenderedContactFields sélectionne les groupes de champs qui apparaissent, depuis ContactFieldsSet.
SharedPtr<MapiContact> contact = MapiContact::FromVCard(u"Contact.vcf");
// the contact travels through an MSG stream into a MailMessage
SharedPtr<IO::MemoryStream> stream = MakeObject<IO::MemoryStream>();
contact->Save(stream, ContactSaveFormat::Msg);
stream->set_Position(0);
SharedPtr<MapiMessage> msg = MapiMessage::Load(stream, MakeObject<MsgLoadOptions>());
SharedPtr<MailMessage> eml = msg->ToMailMessage(MakeObject<MailConversionOptions>());
// RenderVCardInfo writes the contact card into the body
SharedPtr<MhtSaveOptions> mhtSaveOptions = MakeObject<MhtSaveOptions>();
mhtSaveOptions->set_CheckBodyContentEncoding(true);
mhtSaveOptions->set_PreserveOriginalBoundaries(true);
mhtSaveOptions->set_MhtFormatOptions(MhtFormatOptions::WriteHeader | MhtFormatOptions::RenderVCardInfo);
// and these are the field groups it contains
mhtSaveOptions->set_RenderedContactFields(ContactFieldsSet::NameInfo | ContactFieldsSet::PersonalInfo |
ContactFieldsSet::Telephones | ContactFieldsSet::Events);
eml->Save(u"ContactCard.mhtml", mhtSaveOptions);
Lire et définir l’identifiant produit d’un contact
Un fichier vCard enregistre le produit qui l’a créé dans le PRODID champ. Aspose.Email conserve cet identifiant lorsqu’un contact est converti entre vCard et MSG, de sorte que vous pouvez toujours tracer la source d’un contact. L’identifiant est accessible via les membres suivants :
MapiContact::get_ProductId()etMapiContact::set_ProductId()- obtenir ou définir l’identifiant du produit qui a créé un MapiContact.ContactSaveOptions::set_ProductId()- définit l’identifiant écrit lors de l’enregistrement du contact. La méthode est disponible dans toutes les options d’enregistrement de contact, y compris MapiContactSaveOptions et VCardSaveOptions.- VCardExplanatoryInfo::get_ProdId() - renvoie l’identifiant d’un contact chargé avec le VCardContact classe.
L’exemple de code suivant lit l’identifiant du produit à partir d’un fichier vCard, convertit le contact en MSG et l’enregistre avec un nouvel identifiant :
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiContact.h>
#include <Mapi/MapiContactSaveOptions.h>
#include <Mapi/ContactSaveFormat.h>
#include <Mapi/MapiItemType.h>
#include <PersonalInfo/vCard/VCardContact.h>
#include <PersonalInfo/vCard/VCardExplanatoryInfo.h>
#include <system/io/memory_stream.h>
#include <system/console.h>
using namespace System;
using namespace Aspose::Email::Mapi;
using namespace Aspose::Email::PersonalInfo::VCard;
// Read the product identifier from a vCard file
SharedPtr<VCardContact> vcard = VCardContact::Load(u"contact.vcf");
Console::WriteLine(u"vCard product ID: " + vcard->get_ExplanatoryInfo()->get_ProdId());
// The identifier is kept when the contact is converted to MSG
auto msgStream = MakeObject<IO::MemoryStream>();
vcard->Save(msgStream, ContactSaveFormat::Msg);
msgStream->set_Position(0);
SharedPtr<MapiMessage> msg = MapiMessage::Load(msgStream);
if (msg->get_SupportedType() == MapiItemType::Contact)
{
auto contact = System::DynamicCast<MapiContact>(msg->ToMapiMessageItem());
Console::WriteLine(u"MapiContact product ID: " + contact->get_ProductId());
// Save the contact to MSG with a different product identifier
auto options = MakeObject<MapiContactSaveOptions>();
options->set_ProductId(u"-//Contoso//Address Book 2.0//EN");
contact->Save(u"contact_out.msg", options);
}
Pour définir l’identifiant d’un nouveau contact, appelez set_ProductId() ou transmettre l’identifiant via VCardSaveOptions lors de l’enregistrement du contact en tant que vCard :
#include <Mapi/MapiContact.h>
#include <Mapi/ContactSaveFormat.h>
#include <PersonalInfo/vCard/VCardSaveOptions.h>
using namespace System;
using namespace Aspose::Email::Mapi;
using namespace Aspose::Email::PersonalInfo::VCard;
auto contact = MakeObject<MapiContact>(u"John Smith", String(u"john.smith@example.com"));
contact->set_ProductId(u"-//Contoso//Address Book 2.0//EN");
contact->Save(u"contact_out.vcf", ContactSaveFormat::VCard);
// Override the identifier for a single save operation
auto options = MakeObject<VCardSaveOptions>();
options->set_ProductId(u"-//Contoso//Export Tool 1.0//EN");
contact->Save(u"contact_export.vcf", options);
Voir aussi
- Travailler avec des fichiers vCard (VCF) - le format neutre
VCardContactclasse. - Travailler avec les contacts dans un fichier PST - contacts stockés à l’intérieur d’un PST.