Contact Management in Cloud Mail


Requirements: Cloud Mail

Cloud Mail provides a suite of easy-to-use mail and contact management components. This article covers contact management using popular cloud services such as Office 365 (Graph API) and Gmail. For sending mail, please see our Getting Started with Cloud Mail article for more information.

Contents

Gmail

The Gmail component provides an easy-to-use interface to Google Contacts using Google's People API. This component supports listing contacts and contact groups, and creating, updating, and deleting contacts.

OAuth Authentication

Before using the component, it must be authorized via OAuth. The simplest approach is to configure the built-in OAuth property and call the Authorize method. The component's default scopes already include access to contacts.

By design, user interaction is required the first time the component is authorized. When the Authorize method is called, the component starts an embedded web server and launches a browser so the user can sign in and grant access to the application. Once access is granted, the service redirects the browser back to the embedded web server, and the component automatically exchanges the authorization code it receives for an access token. The component then uses the access token in its requests, and automatically obtains a new one when it expires.

Gmail gmail = new Gmail();
gmail.OAuth.ClientProfile = CloudOAuthClientProfiles.cocpApplication;
gmail.OAuth.GrantType = OAuthSettingsGrantTypes.cogtAuthorizationCode;
gmail.OAuth.ClientId = "CLIENT_ID";
gmail.OAuth.ClientSecret = "CLIENT_SECRET";
gmail.Authorize();

Alternatively, the separate OAuth component included in the toolkit can be used to obtain an authorization string, which is then assigned to the Authorization property. The authorization string is valid only for a limited period of time; however, a parameter can be included in the initial authorization to request a refresh token, which can be used without user interaction to update the authorization string. To add an additional parameter, use the AddParam method. In the example below, the "access_type" parameter is set to "offline".

OAuth oauth = new OAuth();
oauth.ClientId = "CLIENT_ID";
oauth.ClientSecret = "CLIENT_SECRET";
oauth.ServerAuthURL = "https://accounts.google.com/o/oauth2/auth";
oauth.ServerTokenURL = "https://accounts.google.com/o/oauth2/token";
oauth.AuthorizationScope = "https://www.googleapis.com/auth/contacts";
oauth.GrantType = OAuthGrantTypes.ogtAuthorizationCode;
oauth.AddParam("access_type", "offline");
gmail.Authorization = oauth.GetAuthorization();

For more information about OAuth authorization, including persisting refresh tokens, web applications, and unattended applications, please see our OAuth Authorization in /n software Cloud Products article.

Creating Contacts

Use the CreateContact method to create a new contact. The new contact is added to the end of the Contacts collection. After creating a contact with basic information, you can update it and set additional fields by editing the contact in the Contacts collection and calling the UpdateContact method. Fields that are not exposed directly on the contact, such as the company name, can be set with the SetContactField method.

// Create a contact. It is added to the end of the Contacts collection.
gmail.CreateContact("Pavel", "Bansky", "pavelb@gmail.com");
int idx = gmail.Contacts.Count - 1;
// Set notes.
gmail.Contacts[idx].Notes = "testNotes";
// Set multiple phone numbers.
gmail.Contacts[idx].PhonesCount = 2;
gmail.Contacts[idx].PhoneIndex = 0;
gmail.Contacts[idx].PhoneType = TGLPhoneTypes.ptMobile;
gmail.Contacts[idx].PhoneNumber = "0123456789";
gmail.Contacts[idx].PhoneIndex = 1;
gmail.Contacts[idx].PhoneType = TGLPhoneTypes.ptWork;
gmail.Contacts[idx].PhoneNumber = "9876543210";
// Set a company name.
gmail.SetContactField(idx, "/json/organizations", "[{\"name\": \"Volkswagen\"}]", 1); // The last argument is the type of the field. 1 (Array)
// Set birthday.
gmail.SetContactField(idx, "/json/birthdays", "[{\"date\": {\"year\": 1999, \"month\": 12, \"day\": 1}}]", 1);
// Set address.
gmail.SetContactField(idx, "/json/addresses", "[{\"city\": \"Sydney\", \"region\": \"New South Wales\", \"postalCode\": \"2000\", \"country\": \"Australia\", \"countryCode\": \"AU\"}]", 1);
// Update the contact.
gmail.UpdateContact(idx);

Listing Contacts

Contacts for the user can be retrieved via the ListContacts method. The ContactList event will fire for each contact, and the Contacts collection will be populated when the method returns. If the number of contacts exceeds the page size, the ListContactsMarker will be populated, and the ListContacts method may be called again to retrieve the next page of contacts. These contacts will be added to the end of the Contacts collection.

do {
  gmail.ListContacts();
} while (gmail.ListContactsMarker.Length > 0);

The user's contact groups can be listed with the ListContactGroups method, which populates the ContactGroups collection.

A specific contact can also be retrieved using the GetContact method. The retrieved contact is added to the end of the Contacts collection.

// Retrieve a contact by its ID.
string contactId = "12345";
gmail.GetContact(contactId);
// Access the retrieved contact.
int idx = gmail.Contacts.Count - 1;
var retrievedContact = gmail.Contacts[idx];
string firstName = retrievedContact.FirstName;
string lastName = retrievedContact.LastName;
// Set the index to 0 to access the first email address.
retrievedContact.EmailAddressIndex = 0;
string email = retrievedContact.EmailAddress;
// Set the index to 0 to access the first phone number.
retrievedContact.PhoneIndex = 0;
string phone = retrievedContact.PhoneNumber;
// Get specific information about the contact.
string birthday = gmail.GetContactField(idx, "/json/birthdays/[1]/date");
string nickname = gmail.GetContactField(idx, "/json/nicknames/[1]/value");

Deleting Contacts

Contacts for the user can be deleted via the DeleteContact method.

// List contacts and search for a contact with the specified name.
gmail.ListContacts();
for (int i = 0; i < gmail.Contacts.Count; i++) {
  if (gmail.Contacts[i].DisplayName == "John Doe") {
    // Delete the contact.
    gmail.DeleteContact(gmail.Contacts[i].Id);
    break;
  }
}

Office365

The Office365 component provides an easy-to-use interface to contact management via Microsoft's Graph API. This component supports listing contacts and contact folders, and creating, updating, and deleting contacts.

OAuth Authentication

Before using the component, it must be authorized via OAuth. The simplest approach is to configure the built-in OAuth property and call the Authorize method. The component's default scopes already include access to contacts.

By design, user interaction is required the first time the component is authorized. When the Authorize method is called, the component starts an embedded web server and launches a browser so the user can sign in and grant access to the application. Once access is granted, the service redirects the browser back to the embedded web server, and the component automatically exchanges the authorization code it receives for an access token. The component then uses the access token in its requests, and automatically obtains a new one when it expires.

Office365 office365 = new Office365();
office365.OAuth.ClientProfile = CloudOAuthClientProfiles.cocpApplication;
office365.OAuth.GrantType = OAuthSettingsGrantTypes.cogtAuthorizationCode;
office365.OAuth.ClientId = "CLIENT_ID";
office365.OAuth.ClientSecret = "CLIENT_SECRET";
office365.Authorize();

Alternatively, the separate OAuth component included in the toolkit can be used to obtain an authorization string, which is then assigned to the Authorization property. The authorization string is valid only for a limited period of time, but including the "offline_access" scope requests a refresh token, which can be used without user interaction to update the authorization string.

OAuth oauth = new OAuth();
oauth.ClientId = "CLIENT_ID";
oauth.ClientSecret = "CLIENT_SECRET";
oauth.ServerAuthURL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
oauth.ServerTokenURL = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
oauth.AuthorizationScope = "offline_access user.read contacts.readwrite";
oauth.GrantType = OAuthGrantTypes.ogtAuthorizationCode;
office365.Authorization = oauth.GetAuthorization();

For more information about OAuth authorization, including persisting refresh tokens, web applications, and unattended applications, please see our OAuth Authorization in /n software Cloud Products article.

Creating Contacts

Use the CreateContact method to create a new contact. The new contact is inserted at the beginning (index 0) of the Contacts collection. After creating a contact with basic information, it may be updated by editing the contact in the Contacts collection and calling the UpdateContact method.

// Create a contact in the main contacts folder. It is inserted at index 0 of the Contacts collection.
office365.CreateContact("Pavel", "Bansky", "pavelb@contoso.com", "");
// Set a company name.
office365.Contacts[0].CompanyName = "Volkswagen";
// Set notes.
office365.Contacts[0].Notes = "testNotes";
// Set multiple phone numbers.
office365.Contacts[0].PhonesCount = 2;
office365.Contacts[0].PhoneIndex = 0;
office365.Contacts[0].PhoneType = TOLPhoneTypes.optMobile;
office365.Contacts[0].PhoneNumber = "0123456789";
office365.Contacts[0].PhoneIndex = 1;
office365.Contacts[0].PhoneType = TOLPhoneTypes.optBusiness;
office365.Contacts[0].PhoneNumber = "9876543210";
// Set birthday.
office365.SetContactField(0, "/json/birthday", "2024-05-21", 2); // The last argument is the type of the field. 2 (String)
// Set business address.
office365.SetContactField(0, "/json/businessAddress", "{\"city\": \"string\", \"countryOrRegion\": \"string\", \"postalCode\": \"string\", \"state\": \"string\", \"street\": \"string\"}", 0); // The last argument is the type of the field. 0 (Object)
// Update the contact.
office365.UpdateContact(0);

Listing Contacts

Contacts for the user can be retrieved via the ListContacts method. The ContactList event will fire for each contact, and the Contacts collection will be populated when the method returns. If the number of contacts exceeds the page size, the ListContactsMarker will be populated, and the ListContacts method may be called again to retrieve the next page of contacts. These contacts will be added to the end of the Contacts collection.

Contacts are organized in contact folders, which can be listed with the ListContactFolders method.

// List root folders (or provide a specific folder Id).
office365.ListContactFolders("");
// List contacts in the first folder.
office365.ListContacts(office365.ContactFolders[0].Id);
// List all contacts.
do {
  office365.ListContacts("");
} while (office365.ListContactsMarker.Length > 0);

A specific contact can also be retrieved using the GetContact method. The retrieved contact is inserted at the beginning (index 0) of the Contacts collection.

// Retrieve a contact by its ID.
string contactId = "12345";
office365.GetContact(contactId);
// Access the retrieved contact.
var retrievedContact = office365.Contacts[0];
string firstName = retrievedContact.FirstName;
string lastName = retrievedContact.LastName;
// Set the index to 0 to access the first email address.
retrievedContact.EmailAddressIndex = 0;
string email = retrievedContact.EmailAddress;
// Set the index to 0 to access the first phone number.
retrievedContact.PhoneIndex = 0;
string phone = retrievedContact.PhoneNumber;
// Get specific information about the contact.
string birthday = office365.GetContactField(0, "/json/birthday");
string middleName = office365.GetContactField(0, "/json/middleName");

Deleting Contacts

Contacts for the user can be deleted via the DeleteContact method.

// List contacts and search for a contact with the specified name.
office365.ListContacts("folder_id");
for (int i = 0; i < office365.Contacts.Count; i++) {
  if (office365.Contacts[i].DisplayName == "John Doe") {
    // Delete the contact.
    office365.DeleteContact(office365.Contacts[i].Id);
    break;
  }
}

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.