Working with vCard (VCF) Files in Java
This article covers the VCardContact class, which reads and writes vCard (VCF) files independently of Outlook and MAPI. To create and manage Outlook MapiContact items — which can also be exported to VCF — see Working with Outlook Contacts.
VCardContact vs MapiContact
Aspose.Email exposes contacts through two different classes, and choosing the right one avoids a lot of confusion:
- VCardContact — a pure vCard object. Use it when your source and target are vCard (VCF) files and you do not need Outlook/MAPI features. It reads and writes VCF directly, supports vCard 2.1/3.0/4.0 and multiple contacts per file.
- MapiContact — an Outlook contact. Use it when you work with MSG/PST or need MAPI-specific properties.
MapiContactcan also import from and export to VCF via itsfromVCardandsavemethods (see Working with Outlook Contacts).
The rest of this article focuses on VCardContact.
Create a vCard and Save It
The VCardContact class has a parameterless constructor and exposes strongly-typed property sets such as VCardIdentificationInfo, VCardOrganization, VCardEmailCollection, VCardTelephoneNumberCollection, and VCardDeliveryAddressCollection.
The following code snippet shows you how to build a contact from scratch and save it as a vCard (VCF) file.
VCardContact contact = new VCardContact();
VCardFullName fullName = new VCardFullName();
fullName.setGivenName("Bertha");
fullName.setMiddleName("A.");
fullName.setFamilyName("Buell");
VCardIdentificationInfo identificationInfo = new VCardIdentificationInfo();
identificationInfo.setDisplayName("Bertha Buell");
identificationInfo.setFullName(fullName);
identificationInfo.setNickname("Bertie");
identificationInfo.setBirthday(new GregorianCalendar(1980, java.util.Calendar.MAY, 20).getTime());
contact.setIdentificationInfo(identificationInfo);
VCardOrganization organization = new VCardOrganization();
organization.setOrganization("Awthentikz");
organization.setTitle("Social work assistant");
contact.setOrganization(organization);
VCardEmail email = new VCardEmail();
email.setEmailAddress("BerthaABuell@example.com");
email.setEmailType(VCardEmailType.INTERNET);
contact.getEmails().addItem(email);
// Save as a vCard (VCF) file
contact.save("contact.vcf");
IdentificationInfo.FullName is a string, in Aspose.Email for Java it is a VCardFullName object with separate given/middle/family name parts.
The Contact Property Model
Beyond the name and email shown above, a VCardContact exposes the full vCard data model through strongly-typed property sets. The snippets below extend the contact created earlier.
Postal Addresses
Postal addresses live in the VCardDeliveryAddressCollection as VCardDeliveryAddress items. The address type takes a combination of VCardDeliveryAddressType flags (HOME, WORK, POSTAL, PARCEL, DOM, INTL, PREF).
VCardContact contact = new VCardContact();
VCardDeliveryAddress address = new VCardDeliveryAddress();
address.setAddressType(VCardDeliveryAddressType.WORK | VCardDeliveryAddressType.PREF);
address.setStreet("4 Darwinia Loop");
address.setLocality("Eighty Mile Beach");
address.setRegion("WA");
address.setPostalCode("6725");
address.setCountryName("Australia");
contact.getDeliveryAddresses().addItem(address);
Telephone Numbers
Phone numbers live in the VCardTelephoneNumberCollection as VCardTelephoneNumber items. The telephone type takes a combination of VCardTelephoneType flags (VOICE, WORK, HOME, CELL, FAX, PAGER, PREF, and more).
VCardContact contact = new VCardContact();
VCardTelephoneNumber workPhone = new VCardTelephoneNumber();
workPhone.setTelephoneNumber("(08) 9080 1183");
workPhone.setTelephoneType(VCardTelephoneType.WORK | VCardTelephoneType.VOICE);
VCardTelephoneNumber mobilePhone = new VCardTelephoneNumber();
mobilePhone.setTelephoneNumber("(925) 599 3355");
mobilePhone.setTelephoneType(VCardTelephoneType.CELL);
contact.getTelephoneNumbers().addItem(workPhone);
contact.getTelephoneNumbers().addItem(mobilePhone);
Geographic Position
The Geo property stores a global position as float latitude and longitude.
VCardContact contact = new VCardContact();
VCardGeo geo = new VCardGeo();
geo.setLatitude(48.858844f);
geo.setLongitude(2.294351f);
contact.setGeo(geo);
Photo
A contact photo is set on IdentificationInfo.Photo as a VCardPhoto. It can be embedded inline from image bytes or referenced by URL. The image format is given by VCardPhotoType and the storage mode by VCardValueLocation.
VCardContact contact = new VCardContact();
contact.setIdentificationInfo(new VCardIdentificationInfo());
// Embed the image bytes inline
VCardPhoto inlinePhoto = new VCardPhoto();
inlinePhoto.setData(Files.readAllBytes(Paths.get("portrait.jpg")));
inlinePhoto.setPhotoType(VCardPhotoType.JPEG);
inlinePhoto.setValueLocation(VCardValueLocation.INLINE);
contact.getIdentificationInfo().setPhoto(inlinePhoto);
// Or reference an external image by URL
VCardPhoto linkedPhoto = new VCardPhoto();
linkedPhoto.setUri("https://example.com/portrait.jpg");
linkedPhoto.setPhotoType(VCardPhotoType.JPEG);
linkedPhoto.setValueLocation(VCardValueLocation.URL);
contact.getIdentificationInfo().setPhoto(linkedPhoto);
Formatted Address Labels
A label is the formatted, ready-to-print text of a delivery address. Labels live in the VCardLabelCollection as VCardLabel items, each tagged with an address type.
VCardContact contact = VCardContact.load("contact.vcf");
for (VCardLabel label : contact.getLabels()) {
System.out.println(label.getAddressType());
System.out.println(label.getAddress());
}
VCardLabel has no public constructor, so labels are read from an existing vCard rather than composed in code. To emit a label into a file you write yourself, fill in the VCardDeliveryAddress fields instead.
Read the Model Back
After loading a vCard, the same property sets expose the parsed data.
VCardContact loaded = VCardContact.load("contact.vcf");
if (loaded.getIdentificationInfo() != null) {
System.out.println(loaded.getIdentificationInfo().getDisplayName());
}
for (VCardDeliveryAddress address : loaded.getDeliveryAddresses()) {
System.out.println(address.getAddressType() + ": " + address.getStreet() + ", " + address.getLocality());
}
for (VCardTelephoneNumber phone : loaded.getTelephoneNumbers()) {
System.out.println(phone.getTelephoneType() + ": " + phone.getTelephoneNumber());
}
if (loaded.getGeo() != null) {
System.out.println("Geo: " + loaded.getGeo().getLatitude() + ", " + loaded.getGeo().getLongitude());
}
Security (Public Key or Certificate)
The VCardSecurity property exposes the public key or authentication certificate stored in the vCard (the KEY property). Its saveToPEM method writes that key to a PEM file.
VCardContact signed = VCardContact.load("signed.vcf");
if (signed.getSecurity() != null && signed.getSecurity().getKey() != null) {
System.out.println("Key type: " + signed.getSecurity().getType());
// Export the embedded public key / certificate to a PEM file
signed.getSecurity().saveToPEM("public-key.pem");
}
Load a vCard
Use the static VCardContact.load method to read a vCard from a file or a stream. Once loaded, the contact’s properties are available through the same property sets used when creating it.
// Load from a file
VCardContact contact = VCardContact.load("contact.vcf");
System.out.println(contact.getIdentificationInfo().getDisplayName());
// Load from a stream
try (InputStream stream = Files.newInputStream(Paths.get("contact.vcf"))) {
VCardContact fromStream = VCardContact.load(stream);
System.out.println(fromStream.getIdentificationInfo().getDisplayName());
}
Load with a Specific Encoding
To control the text encoding used while reading, pass a VCardLoadOptions object with its preferred encoding set.
VCardLoadOptions loadOptions = new VCardLoadOptions();
loadOptions.setPreferredEncoding(StandardCharsets.UTF_8);
VCardContact contact = VCardContact.load("contact.vcf", loadOptions);
Read Multiple Contacts from a Single File
A vCard file may contain more than one contact. Use the static isMultiContacts method to check whether a file or stream holds multiple contacts, and loadAsMultiple to read them all into a List<VCardContact>. Both methods have file, stream, and load-options overloads:
static boolean isMultiContacts(String filePath)/isMultiContacts(InputStream stream)static List<VCardContact> loadAsMultiple(String filePath)/loadAsMultiple(String filePath, VCardLoadOptions options)static List<VCardContact> loadAsMultiple(InputStream stream)/loadAsMultiple(InputStream stream, VCardLoadOptions options)
try (InputStream stream = Files.newInputStream(Paths.get("contacts.vcf"))) {
if (VCardContact.isMultiContacts(stream)) {
List<VCardContact> contacts = VCardContact.loadAsMultiple(stream);
for (VCardContact contact : contacts) {
System.out.println(contact.getIdentificationInfo().getDisplayName());
}
}
}
isMultiContacts(InputStream) reads the stream to detect the number of contacts. Reopen the stream (or use the file-path overloads) before calling loadAsMultiple on the same source.
Save Options
The VCardSaveOptions class customizes how a contact is written:
Version— the output vCard version from the VCardVersion enumeration:V21(vCard 2.1, the default),V30(3.0), orV40(4.0).PreferredTextEncoding— the encoding used when writing the file.UseExtensions— whether extended (X-) properties may be written. The default istrue.ProductId— the value written to thePRODIDproperty.
VCardContact contact = VCardContact.load("contact.vcf");
VCardSaveOptions saveOptions = new VCardSaveOptions();
saveOptions.setVersion(VCardVersion.V30); // write vCard 3.0 (the default is V21)
saveOptions.setPreferredTextEncoding(StandardCharsets.UTF_8); // encoding used when writing
saveOptions.setUseExtensions(true); // allow extended (X-) properties
saveOptions.setProductId("My Company"); // PRODID value
contact.save("contact_v3.vcf", saveOptions);
The version can also be passed straight to the constructor:
VCardContact contact = VCardContact.load("contact.vcf");
contact.save("contact_v4.vcf", new VCardSaveOptions(VCardVersion.V40));
See Also
- Working with Outlook Contacts — create, save, and read Outlook
MapiContactitems, including VCF import and export. - Working with Contacts in PST File — store and read contacts inside a PST.