Create, Save, and Load Outlook Contacts in C++
Aspose.Email for C++ allows you to create and manage Microsoft Outlook contacts programmatically. The MapiContact class provides all contact-related properties including names, professional info, addresses, email accounts, phone numbers, categories, custom fields, and photos.
This article demonstrates how to create, save, and read Outlook contacts in MSG and vCard (VCF) formats.
The samples in this article use these headers and namespaces:
#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;
Create and Save an Outlook Contact
To create an Outlook contact and save it to disk, follow the steps below:
- Instantiate MapiContact.
- Populate name, professional, personal, and address details.
- Add electronic addresses and telephone numbers.
- Assign categories, mileage, billing, and custom fields.
- Optionally, embed a contact photo.
- Save the contact in MSG or vCard (VCF) format.
The details of a contact are grouped into property sets: MapiContactNamePropertySet for the name, MapiContactProfessionalPropertySet for the company and job title, MapiContactPhysicalAddressPropertySet for the postal addresses, MapiContactElectronicAddressPropertySet for e-mail and fax addresses, MapiContactTelephonePropertySet for the phone numbers and MapiContactOtherPropertySet for the remaining fields such as the reminder and the user fields. MapiContact::Save writes the contact as MSG or as vCard, depending on the 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);
Read a Contact using MapiContact
The MapiContact class can load Outlook contacts saved in both MSG and VCF formats.
Load a Contact from MSG
An MSG file holding a contact is loaded like any other Outlook item, with MapiMessage::Load. ToMapiMessageItem then returns the item as a MapiContact. Checking get_SupportedType first makes sure the file really holds a contact - DynamicCast throws when the item is of another 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());
}
Load a Contact from vCard (VCF)
A vCard file can be read in two ways. VCardContact::Load gives a VCardContact that mirrors the vCard structure - the right choice when the data stays in vCard form (see Working with vCard Files). MapiContact::FromVCard converts the vCard straight into an Outlook contact, ready to be saved as MSG or added to a PST file.
// 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());
Control How a vCard Is Read and Written
MapiContact::FromVCard has overloads that take a VCardLoadOptions object or an encoding, which matters for files written in a legacy code page. On the way out, VCardSaveOptions chooses the vCard version and decides through UseExtensions whether the extended X- properties may be written - switch it off when the target application only understands the standard fields.
// 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);
Distribution Lists and Multi-Contact VCF Files
A VCF file that holds several contacts maps onto a MapiDistributionList: FromVCF reads such a file, and MapiDistributionListSaveOptions with ContactSaveFormat::VCard writes one back.
// 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);
Render a Contact as MHTML
A contact card can be published as MHTML - an email-friendly page that shows the fields the way Outlook does. The contact is saved into an MSG stream, read back as a MapiMessage, converted to a MailMessage and saved with MhtFormatOptions::RenderVCardInfo. RenderedContactFields selects the groups of fields that appear, from 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);
Read and Set the Product Identifier of a Contact
A vCard file records the product that created it in the PRODID field. Aspose.Email keeps this identifier when a contact is converted between vCard and MSG, so you can always trace the source of a contact. The identifier is available through the following members:
MapiContact::get_ProductId()andMapiContact::set_ProductId()- get or set the identifier of the product that created a MapiContact.ContactSaveOptions::set_ProductId()- sets the identifier written when the contact is saved. The method is available in all contact save options, including MapiContactSaveOptions and VCardSaveOptions.- VCardExplanatoryInfo::get_ProdId() - returns the identifier of a contact loaded with the VCardContact class.
The following code sample reads the product identifier from a vCard file, converts the contact to MSG, and saves it with a new identifier:
#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);
}
To set the identifier for a new contact, call set_ProductId() or pass the identifier through VCardSaveOptions when saving the contact as a 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);
See Also
- Work with vCard (VCF) Files - the format-neutral
VCardContactclass. - Working with Contacts in PST File - contacts stored inside a PST.