How to send a vCard with MMS using C# and .NET

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

Send vCards via MMS using C# and .NET

You can use the Twilio Programmable Messaging to send contact information in vCard format via MMS. If you have a business with many users and you must send contact information, you should consider sending it over MMS. You can also send vCards via WhatsApp, but using MMS will allow you to reach anyone even if they don't use WhatsApp. In this post, you will see how to generate and send vCards over MMS programmatically using C# .NET.

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 MMS, 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.

Buy a number

You'll need to have a phone number to send MMS messages.

In order to buy one, in the Twilio Console, you need to go to the left side menu, select the "Phone Numbers" option, then "Manage" to finally click "Buy a number".

Left side menu specifying the "Buy a number" option in the "Phone Numbers" category.

In the filters on the displayed screen, select a country that has the MMS option available, for example, the USA.

Form to filter Twilio Phone Numbers to buy, with the phone country options, and the available functions, SMS, MMS, Fax and Voice.

Select one of the available numbers by clicking on the "Buy" option.

List of phone numbers available to buy with the filters applied in the form.

A screen will be displayed indicating the properties of your phone number before buying it. Here you can verify that the ability to send MMS is available. Finally, click on "Buy <phone number>"

Modal screen with the phone number to buy, with monthly cost and available capacities.

Footer of the modal screen with the phone number to buy, with the "Buy <number>" button to confirm it.

Finally, a screen will be displayed with the confirmation of your new phone number available to use.

Confirmation screen of the phone number purchased.

Set up your account for Messaging Service

Next, you will need to configure the Messaging Service where you can associate your phone number with the service.

You can also send MMS straight from Twilio Phone Numbers without using a Messaging Service, however, later in this post, you'll use message scheduling which requires a Messaging Service.

In The Twilio 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"). Then, click on "Services".

Left side menu with the Messaging menu open, and the Services option selected.

Next, on the displayed page, click the "Create Messaging Service" button to configure your service.

Messaging Service home page explaining the functionality and with the "Creating Messaging Service" button

Enter a name that identifies what you will do with your service, select what you are going to use your service for in the available list, and finally click on "Create Messaging Service".

Messaging Service creation screen, with the name of the service, the list of options on the use of the service and the button to create it.

Your service has been created. Now it is time to configure a sender, that is, a phone number from which you will send the messages.

You can only send so many messages per second with a single phone number or sender. With Messaging Services, you can add multiple senders to its Sender Pool, and instead of sending messages directly from a single sender, you can send them via the Messaging Service to increase the message throughput.

In addition to phone numbers, you can also add short codes, alpha senders, and WhatsApp numbers.

Second step in "Messaging Service Setup", to configure the Sender Pool with the option to add new senders (phone numbers, whatsapp numbers) with the "Add Senders" button, which can be used when sending messages through the Messaging Service created.

Click on the "Add Senders" button and in the modal screen that will be displayed, select the "Phone Number" option in the "Sender Type" dropdown, and finally click on "Continue".

Modal screen to add a sender, specifying that it will be a phone number

You will see the list of phone numbers available in your account (the one you just bought). Select the checkbox for that number, which appears in the first column, and then click "Add Phone Numbers".

List of phone numbers available as senders in your account to add them in the messaging service

Then, click "Set up integration", where you can configure what to do with incoming messages on your senders and the maximum time your messages can be queued before not being sent (like a timeout).

Select the "Drop the message" option, since you won't be doing anything with incoming messages in this project.

Integration screen, with the "Drop the message" option for incoming messages and keeping the default value for the "Validity Period" field.

Then click the "Step 4: Add compliance ratio" button.

Footer of the integration form, with the button "Step 4: Add compliance info"

In this form, you should configure topics such as your business profile, among others, to ensure that you are making good use of messaging in your business.

In this project, you will skip this step and click "Complete Messaging Service Setup" to finish the process.

Footer of the compliance step, with the "Complete Messaging Service Setup" button

After finishing the process, a modal screen will be displayed with the confirmation of this process. Click on the "View my new Messaging Service" button.

Modal confirmation screen of the messaging service created, with the options to view the service and try to send a message.

On the screen of your new service, you will see the Messaging Service SID, which you should copy, since you will use it in your code to send the MMS message.

Summary screen of the created service, with the name of the service, the selected use case and the unique SID that will be used in the project.

Alright, now that you've set up your Twilio number and messaging service for your project, it's time to set up a file hosting service and your .NET project.

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.

Command line with the execution of ngrok, which shows various data, including the Forwarding (HTTPS address) must be copied to be used in the project.

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 TwilioMMSvCard
cd TwilioMMSvCard

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>"
dotnet user-secrets set "TwilioMessagingServiceSid" "<Twilio Messaging Service Sid>"

Replace <Twilio Account SID> with the Twilio Account SID, <Twilio Auth Token> with the Auth Token, and <Twilio Messaging Service Sid> with the Messaging Service Sid 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 can write code to generate vCard files yourself or use an existing library that does this for you. In this tutorial, you will use vCardLib to create the vCards to share contact information.

dotnet add package vCardLib.dll

Additionally, you will install the Twilio SDK to send MMS 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;
using Twilio.Types;

The code above adds all the namespaces 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 twilioMessagingServiceSid = configuration["TwilioMessagingServiceSid"];
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

Next up, 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 generated a vCard file that you may have used before as a user when sending or receiving contacts on your phone. It's time to send it over MMS using the Twilio SDK.

Share contact information via MMS

To send the MMS, you have to initialize the Twilio SDK with your credentials (Account SID and Auth Token), create the message with some options, and then send it. As you can see, you will use the CreateMessageOptions class with some properties, first specifying in the constructor the destination phone number of the message. Next, configure the Body property with a text message, the MediaUrl where you specify the URL of the vCard file publicly served through ngrok, the SendAsMms to specify that it will be an MMS message, and finally the MessagingServiceSid with the identifier of the previously created Messaging Service.

TwilioClient.Init(twilioAccountSid, twilioAuthToken);
var messageOptions = new CreateMessageOptions(new PhoneNumber("<to number>"));
messageOptions.Body = "This is the main contact for Néstor.";
messageOptions.MediaUrl = new List<Uri>() { new Uri(serverUrl + vCardFileName) };
messageOptions.MessagingServiceSid = twilioMessagingServiceSid;

var message = MessageResource.Create(messageOptions);

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

// wait a couple of seconds before deleting the file,
// so Twilio can download the file and send it as MMS
await Task.Delay(5000);

File.Delete(savePath);

Replace  <to number> with your personal phone number for testing.

Also,  after creating your message in Twilio, the file will be deleted as it might not be needed anymore.

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

dotnet run

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

A few seconds later, you should receive a message with a contact card.

Depending on your mobile device, the messaging app, the mobile provider you have, and the country, the way the vCard file appears may vary. In some cases, instead of appearing as a contact card directly, it will appear as a Twilio link to download the file, which you will be able to import to your phone successfully.

Schedule the message

When you send messages, especially with a high volume and if users do not request it before, you must be careful not to send them outside of normal hours for your users (at night, early morning) to avoid being considered SPAM, both by your users and the mobile providers of the country where you send the messages.

To do this, with the same CreateMessageOptions class you can specify to send the MMS later with the SendAt property. The message will be created in the Twilio API with a "scheduled" status, and Twilio will send the MMS when the specified time arrives.

You must also specify the schedule type, through the ScheduleType property.

TwilioClient.Init(twilioAccountSID, twilioAuthToken);
var messageOptions = new CreateMessageOptions(new PhoneNumber("<to number>"));
messageOptions.Body = "This is the main contact for Néstor.";
messageOptions.MediaUrl = new List<Uri>() { new Uri(serverUrl + vCardFileName) };
messageOptions.SendAsMms = true;
messageOptions.MessagingServiceSid = twilioMessagingServiceSid;
messageOptions.SendAt = DateTime.UtcNow.AddMinutes(20);
messageOptions.ScheduleType = MessageResource.ScheduleTypeEnum.Fixed;

var message = MessageResource.Create(messageOptions);

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

Since the message is not yet processed and sent, you cannot delete the vCard file from your file hosting server until it is sent.

Now run the console again. You will be able to verify that the status of the message changes from Queue to Scheduled.

dotnet run

Console screen with the generated message ID and the scheduled status.

Future improvements

Now you can send contact information via MMS, 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.
  • You can add webhooks in your messages to check the final status of the message (sent, rejected, with errors, etc.).
  • You could poll for the status of the MMS every couple of seconds to check if the message has been sent, and then delete the vCard file.

Additional resources

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

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

How to Send Scheduled SMS with C# .NET and Twilio Programmable Messaging - This post will walk you through scheduling SMS which you can also use for scheduling MMS.

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.