Getting Started with Cloud Mail


Requirements: Cloud Mail

Cloud Mail provides a suite of easy-to-use mail management components. These components make it possible to quickly and securely send, receive, and manage mail using popular cloud services such as Office 365 (Graph API), Amazon SES, and Gmail. To send mail through any of these services with a single interface, please see our Using CloudMailer to Send Emails article.

To use SMTP, IMAP, or POP instead, please see our Using OAuth with the SMTP, IMAP, and POP Components article for more information on combining OAuth with the IPWorks mail components.

Contents

Amazon SES

The AmazonSES component provides a simple interface to Amazon's Simple Email Service. The component supports sending both plaintext and HTML emails; adding, listing, and removing identities; verifying domains and email addresses; and gathering administrative data.

Authentication

After signing up for Amazon SES, an access key and a secret key are provided. Before making any requests to Amazon, set these values in the AccessKey and SecretKey properties. By default, the component makes requests against the us-east-1 region, and the Region configuration setting can be used to select a different one.

AmazonSES amazonses = new AmazonSES();
amazonses.AccessKey = "MY_ACCESS_KEY";
amazonses.SecretKey = "MY_SECRET_KEY";
// Optionally, select a region other than the default (us-east-1).
amazonses.Config("Region=eu-west-1");

Sending Messages

Messages are sent using the component's Send method. Before calling the method, set MessageHTML or MessageText along with From, Subject, and SendTo. Attachments can be added by calling the AddAttachment method with the path to a local file.

amazonses.From = "verified.email@example.com";
amazonses.SendTo = "recipient@example.com";
amazonses.Subject = "Test SES Email";
amazonses.MessageHTML = "<html><body><b>Hello World!</b></body></html>";
amazonses.AddAttachment("C:\\reports\\file1.zip");
amazonses.Send();

For more information about adding attachments, please see our Including Attachments with Cloud Mail article.

Gmail

The Gmail component provides an easy-to-use interface to Gmail using Google's REST API. The component supports sending and retrieving messages, adding and removing labels on messages, and other functionality.

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 mail.

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 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://mail.google.com/";
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.

Sending Messages

There are two ways to send messages using the Gmail component. The SendMail method sends a message directly. Alternatively, the CreateDraft method creates a draft, which can then be sent using the SendDraft method. In both cases, the details of the new message are specified using the message properties (MessageSubject, MessageBodyContent, MessageTo, MessageCc, etc.).

// Send a message directly.
gmail.MessageSubject = "Subject Text";
gmail.MessageBodyContentType = "text";
gmail.MessageBodyContent = "Body Text";
gmail.MessageTo = "recipient@example.com";
gmail.SendMail();
// Create a draft, and then send it.
gmail.MessageSubject = "I am sending an email.";
gmail.MessageBodyContentType = "text";
gmail.MessageBodyContent = "Just wanted to let you know.";
gmail.MessageTo = "recipient@example.com";
gmail.CreateDraft();
string messageId = gmail.MessageInfo[0].Id;
gmail.SendDraft(messageId);

Retrieving Messages

Information about messages fetched by the component is available in the MessageInfo collection. MessageInfo is populated when the ListMessages, RetrieveMessageInfo, ListDrafts, or Search methods are called.

The ListMessages method lists the messages in the mailbox. The filter and threadId parameters can be used to retrieve a subset of the messages, or both can be left empty to retrieve all messages.

// List all messages. The filter and threadId parameters are empty.
gmail.ListMessages("", "");

By default, the component fetches one page of 100 messages when ListMessages is called. If additional messages remain in the mailbox, the NextPageToken property will be populated. If ListMessages is then called again with the same filter and threadId, the next page of messages will be fetched and added to the MessageInfo collection. The example below populates MessageInfo with all the messages in the mailbox.

do {
  gmail.ListMessages("", "");
} while (gmail.NextPageToken.Length > 0);

The page size can be changed using the MessagePageSize configuration setting.

gmail.Config("MessagePageSize=500");

The component also provides methods to retrieve specific parts of a message: RetrieveMessage, RetrieveMessageHeaders, and RetrieveMessageRaw. Each method takes the ID of the message, which can be found in the MessageInfo collection. After RetrieveMessage is called, the parts of the message are available in the MessageParts collection.

Note that RetrieveMessage moves the retrieved message to the beginning of the MessageInfo collection. To retrieve several messages, gather their IDs first, and then retrieve each one.

// List all messages in the mailbox.
do {
  gmail.ListMessages("", "");
} while (gmail.NextPageToken.Length > 0);
// Gather the IDs of the messages.
List<string> messageIds = new List<string>();
foreach (GLMessageInfo messageInfo in gmail.MessageInfo) {
  messageIds.Add(messageInfo.Id);
}
// Retrieve each message, and print its plaintext body.
foreach (string id in messageIds) {
  gmail.RetrieveMessage(id);
  foreach (GLMessagePart part in gmail.MessageParts) {
    if (part.ContentType.Equals("text/plain")) Console.WriteLine(part.Data);
  }
}

Labels can be added to or removed from a message using the AddMessageLabels and RemoveMessageLabels methods, which take the ID of the message and a semicolon-separated list of labels.

gmail.AddMessageLabels(messageId, "IMPORTANT;STARRED");
gmail.RemoveMessageLabels(messageId, "UNREAD");

Office365

The Office365 component supports sending or creating new messages; retrieving, moving, or copying existing messages; creating, deleting, or copying folders; and other operations supported by the Microsoft Graph API.

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 read and write access to mail.

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 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 mail.readwrite mail.send mailboxsettings.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.

Sending Messages

There are two ways to send messages using the Office365 component. The SendMail method sends a message directly. Alternatively, the CreateDraft method creates a draft, which can then be sent using the SendDraft method. In both cases, the details of the new message are specified using the message properties (MessageSubject, MessageBodyContent, MessageTo, MessageCc, etc.).

// Send a message directly, and save a copy to the Sent Items folder.
office365.MessageSubject = "Subject Text";
office365.MessageImportance = "Low";
office365.MessageBodyContentType = "text";
office365.MessageBodyContent = "Body Text";
office365.MessageTo = "recipient@example.com";
office365.SendMail(true);
// Create a draft, and then send it.
office365.MessageSubject = "Subject Text";
office365.MessageImportance = "Low";
office365.MessageBodyContentType = "text";
office365.MessageBodyContent = "Body Text";
office365.MessageTo = "recipient@example.com";
office365.CreateDraft(0, "");
string messageId = office365.MessageInfo[0].Id;
office365.SendDraft(messageId);

The Office365 component also provides methods for replying to and forwarding messages. The Reply, ReplyAll, and Forward methods send a reply or forward directly. Alternatively, the CreateDraft method can create a reply, reply-all, or forward draft (using a draft type of 1, 2, or 3, respectively), which can then be sent using the SendDraft method.

Unlike drafts of new messages, reply and forward drafts are not built from the message properties. Instead, the draft is created first, and then its fields are set using the MessageInfo collection and saved using the Update method. The new draft is inserted at the beginning (index 0) of the MessageInfo collection.

// Create the reply draft.
string originalMessageId = "MESSAGE_ID";
office365.CreateDraft(1, originalMessageId);
// Set the fields of the new draft.
office365.MessageInfo[0].To = "recipient@example.com";
office365.MessageInfo[0].Subject = "Subject Text";
office365.MessageInfo[0].BodyContentType = "text";
office365.MessageInfo[0].BodyContent = "Body Text";
// Save the changes to the draft.
office365.Update(office365.MessageInfo[0].Id);
// Send the draft.
office365.SendDraft(office365.MessageInfo[0].Id);

Retrieving Messages

Information about messages fetched by the component is available in the MessageInfo collection. MessageInfo is populated when the ListMessages, RetrieveMessage, Search, or ListChanges methods are called.

The ListMessages and ListChanges methods list the messages, or the changed messages, in the folder specified by a folder ID. To get the ID of a folder, the folders can be listed using the ListFolders method, which populates the Folders collection.

// Find the ID of the folder.
string folderId = "";
office365.ListFolders(""); // Lists the folders in the root of the mailbox.
for (int i = 0; i < office365.Folders.Count; i++) {
  if (office365.Folders[i].DisplayName.Equals("SpecificFolderName")) {
    folderId = office365.Folders[i].Id;
    break;
  }
}
// List the messages in the folder.
office365.ListMessages(folderId, "");

By default, the component fetches one page of 100 messages when ListMessages is called. If additional messages remain in the folder, the ListMessagesMarker property will be populated. If ListMessages is then called again on the same folder, the next page of messages will be fetched and added to the MessageInfo collection. The example below populates MessageInfo with all the messages in a particular folder.

do {
  office365.ListMessages(folderId, "");
} while (office365.ListMessagesMarker.Length > 0);

The page size can be changed using the MessagePageSize configuration setting.

office365.Config("MessagePageSize=500");

For more information about working with folders, as well as moving and copying messages, please see our Organizing an Office 365 Mailbox with Cloud Mail article.

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