How to send vCards with WhatsApp using C# and .NET

July 05, 2022
Written by
Néstor Campos
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Send vCards with WhatsApp and C#

You can use the Twilio Programmable Messaging to send contact information in vCard format via WhatsApp. If you use WhatsApp regularly, on some occasions you may have had to send or receive the contact info of a person to whom you must text or call. In this post, you will see how to do this programmatically.

Prerequisites

You will need the following for your development environment:

You can find the source code of this tutorial in this GitHub repository.

What is vCard?

vCard is a standard format for sharing contact information between people and applications. This information may include personal information, phone numbers, email addresses, employment information, and more.

It is used in mail applications such as Outlook and Gmail, in messaging systems such as WhatsApp and Telegram, and in any system that requires the transfer of contact information.

Configure Twilio

Get your Twilio Credentials

In your Twilio account, you will need to obtain the Account SID and the Auth Token to use the Twilio SDK. You can find your Account SID and Auth Token on the home page of your Twilio console.

Twilio console home page showing Account SID and Auth Token to copy them and use them in the application through SDK or some client.

Copy them in a safe place because you will use them later.

If you have a trial account, you can only send messages to verified numbers on the account.

Set up your account for Twilio WhatsApp

To send WhatsApp messages through your Twilio account, you need to have your account enabled for it. In this tutorial, you are going to use the Sandbox available to test your applications.

In real projects, you will need to request access to Twilio to get your actual number, by linking your Twilio account to Facebook Business Manager.

In order to get to the WhatsApp sandbox settings option where you are going to start, in the left-side menu of your console click on "Messaging" (if you don't see it, click on "Explore Products", which will display the list with the available products and there you will see "Messaging"). After that, in the available options open the "Settings" submenu, and finally, click on "WhatsApp sandbox settings".

Side menu in the Twilio console, highlighting the "WhatsApp sandbox Settings" option.

Next, you have to follow the instruction on the screen, in which you must send a pre-defined message to an indicated number through WhatsApp. This will enable that WhatsApp number to use in test mode to send messages to your own WhatsApp number (if you want to send messages to other numbers, the people who own those numbers will have to do this same step).

Twilio Sandbox for WhatsApp form with the settings to enable your Twilio Phone Number.

After that, you will receive a message in response confirming the Sandbox is configured.

Confirmation message on WhatsApp indicating that the number is available to be used in test mode.

Create a static file host

To send vCard files through Twilio with the SDK, you need to make those files available via a public URL, and for that, you'll need to use static file hosting. For this tutorial, you are going to use ngrok to expose a local directory via a public URL.

First, create a folder where you will store the vCard files. This folder can be located anywhere on your machine.

If this is your first time using ngrok, you need to register on ngrok's website, and add the authentication token in the console as the first command:

ngrok authtoken <token from https://dashboard.ngrok.com/get-started/your-authtoken>

Now, run ngrok with the following command, specifying a folder path where you will save your vCard files:

ngrok http file:///<folder path>

Replace <folder path> with the full path to the folder where your vCard files will be located.

Copy the Forwarding HTTPS address that ngrok created for you, as you will use it in your .NET project.

Result of creating an ngrok tunnel in console. The output shows an HTTP and HTTPS Forwarding URL.

With ngrok you can quickly run a public file server, but you could use any file hosting service or even serve the files from ASP.NET Core. If you only want Twilio to be able to read your files, you can validate the X-Twilio-Signature header, and reject the HTTP request if invalid. Read more about validating Twilio requests here.

Create a Console Project

You will need to create a console project using the .NET CLI. Open a console terminal and run the following commands to create a folder that will contain your project:

mkdir TwiliovCard
cd TwiliovCard

Next, create the project with the command below:

dotnet new console

Add the API Key in the project

To add the Twilio Credentials into your project, you will use user secrets since it is a good option for local development that is easy to manage, more secure, and follows good development practices.

To set user secrets for your project, run the following commands at the command line inside your project's root folder:

dotnet user-secrets init
dotnet user-secrets set "TwilioAccountSid" "<Twilio Account SID>"
dotnet user-secrets set "TwilioAuthToken" "<Twilio Auth Token>"

Replace <Twilio Account SID> with the Twilio Account SID and <Twilio Auth Token> with the Auth Token you copied earlier.

To load user secrets, you must add the Microsoft.Extensions.Configuration.UserSecrets NuGet package. Add the package using the following command:

dotnet add package Microsoft.Extensions.Configuration.UserSecrets

Install the Twilio and vCard libraries

You create vCard files manually or install a library that simplifies the process. You will use vCardLib to create and generate the contact information to share.

dotnet add package vCardLib.dll

Additionally, you will install the Twilio SDK to be able to send WhatsApp messages.

dotnet add package Twilio

Configure the project

Now, in the Program.cs file, replace all existing code with the following:

using vCardLib.Models;
using vCardLib.Enums;
using vCardLib.Serializers;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Microsoft.Extensions.Configuration;

The code above imports all the libraries you'll use in the project.

Next, you are going to add the code that loads the configuration from your user secrets, where you stored the Twilio credentials. You will also add the Forwarding URL that ngrok gave you, and the full path of the folder where the vCard files will be stored.

IConfigurationRoot configuration = new ConfigurationBuilder()
    .AddUserSecrets<Program>()
    .Build();

string twilioAccountSid = configuration["TwilioAccountSid"];
string twilioAuthToken = configuration["TwilioAuthToken"];
string serverUrl = "<ngrok URL>/"; // has to end with one '/'
string vCardFolder = "<full folder path>";

Replace <ngrok URL> with the ngrok Forwarding URL and <full folder path> with the full path of the folder that stores the vCard files.

Create contact information with vCard

Now you are going to generate the contact information for a person using the vCardLib library. In the code presented below, you are adding the first name, last name, and a phone number (to which you can specify if it is a work phone, personal phone, or another). Then, you serialize the information to obtain a string with the data following the vCard standard to finally save it as a file in the corresponding folder.

vCard vCardData = new vCard
{
    FamilyName = "Campos",
    GivenName = "Néstor",
    PhoneNumbers = new List<TelephoneNumber>{
        new TelephoneNumber {
            Type = TelephoneNumberType.Work,
            Value = "<phone number>",
            CustomTypeName = "Main contact"
        }
    }
};


string serializedvCardData = Serializer.Serialize(vCardData);

string vCardFileName = "ncampos.vcf";
string SavePath = Path.Combine(vCardFolder, vCardFileName);
File.WriteAllText(SavePath, serializedvCardData);

Change the contact info as you wish.

What you have just done is generate a vCard file that you may have used before as a user when sending or receiving contacts on WhatsApp. It's time to send it using the Twilio SDK.

Share contact information on WhatsApp

Now you have to initialize the Twilio SDK with your credentials (Account SID and Auth Token), create the message, and then send it. As you can see, in the mediaUrl property of the message, you specify the URL of the vCard file, saved in the folder intended for it and exposed through ngrok.

TwilioClient.Init(twilioAccountSid, twilioAuthToken);

var message = MessageResource.Create(
    body: "This is the main contact for Néstor.",
    from: new Twilio.Types.PhoneNumber("whatsapp:<from number>"),
    to: new Twilio.Types.PhoneNumber("whatsapp:<to number>"),
    mediaUrl:new List<Uri>() { new Uri(serverUrl + vCardFileName) }
);


Console.WriteLine($"Message SID: {message.Sid}");
Console.WriteLine($"Message Status: {message.Status}");

Replace <from number> with the phone number (in E. 164 format which includes the country and area code, starting with the + sign) that Twilio has assigned to you in the Sandbox (the same one you used when you sent a message to enable your phone number on the platform). And replace  <to number> with your phone number or any other number that has gone through the validation process in your account.

Sending messages on WhatsApp with Twilio through the SDK uses the same classes and methods as sending SMS and MMS. When specifying the sender and receiver of the message, you will have to prefix "whatsapp:" and then the complete phone number.

Now, run your console project to send your first vCard contact with WhatsApp:

dotnet run

To run the project in Visual Studio Code, press Ctrl + F5 to run.

A few seconds later, you should receive a message on WhatsApp similar to the following:

WhatsApp message received with the Twilio Sandbox number. The Sandbox sent a message with the contact information using a vCard format.

Future improvements

Now you can send contact information via WhatsApp, but you can further improve it:

  • vCard is a very complete standard, the more information you add about the contacts before sending it, the easier it is for the recipient to know which means of contact to use to write or call the other person, what company they work for, and more. The vCardLib library provides you with more classes to add all that information.
  • You could use a real static file host service that will scale with your application. Alternatively, you could serve your files via ASP.NET Core and validate that the HTTP request came from Twilio, and reject it if not.
  • Depending on your needs, you may not want to keep the generated files around. You could automatically clean up the files in multiple ways, like run a script every couple of minutes.

Additional resources

Check out the following resources for more information on the topics and tools presented in this tutorial:

Twilio WhatsApp – This page contains all the information about the requirements and benefits of using messaging over WhatsApp with Twilio.

Twilio SDK for C# and .NET – You can explain all the options provided by the Twilio C# SDK.

Source Code to this tutorial on GitHub - You can find the source code for this project at this GitHub repository. Use it to compare solutions if you run into any issues.

Néstor Campos is a software engineer, tech founder, and Microsoft Most Value Professional (MVP), working on different types of projects, especially with Web applications.