Published on

Next-Level Email Automation With Microsoft Graph

8 min read
Authors
  • avatar
    Name
    Ivan Gechev
    Twitter

In this post, we'll look into the features of Microsoft Graph and explore how they can revolutionize our email communication. From sending emails programmatically to advanced email search capabilities, We'll uncover the possibilities that Azure and Microsoft Graph offer. Get ready to unlock a new level of efficiency and productivity as we explore the exciting world of next-level email automation!

The Significance of Email Automation

In the digital age we live in, email communication remains a vital channel for both personal and professional interactions. However, the volume of emails can quickly skyrocket, leading to inefficiencies and information overload. This is where email automation steps in, offering significant advantages in terms of productivity and time-saving. By automating various aspects of email communication, we can streamline our workflows by improving response times and delivering messages at scale. To ease the work process, I'll explore a few ways that can revolutionize the way we communicate, ultimately enhancing efficiency and productivity.

Exploring Email Automation Features With Microsoft Graph

To be able to use Microsoft Graph and Azure you need an active Azure subscription. You also need to be familiar with how to authenticate your Microsoft Graph Client. If you don't know how to do that, do not fret, I've already covered the various approaches that can be used in this post.

Sending Emails With Microsoft Graph

We can send emails with Microsoft Graph with very little effort or coding needed. Let's do this the proper way and start by defining an interface for the service we will use to send emails:

IEmailService.cs
public interface IEmailService
{
    Task SendMessageAsync(
        string sender,
        string recipient,
        string subject,
        string body,
        CancellationToken cancellationToken = default);
}

We define an interface called IEmailService, which includes the SendMessageAsync method. We will use it to send emails asynchronously. The method requires the sender and recipient's email addresses, the subject, and the body of the email. Additionally, a CancellationToken parameter is provided for handling the cancellation of the operation.

Then, we move to the service itself:

EmailService.cs
public class EmailService : IEmailService
{
    private readonly GraphServiceClient _graphClient;

    public EmailService()
    {
        var environmentCredential = new EnvironmentCredential();
        var scopes = new[] { "https://graph.microsoft.com/.default" };
        _graphClient = new GraphServiceClient(environmentCredential, scopes);
    }
}

We create the EmailService class that implements the EmailService interface. Within the constructor, we instantiate an EnvironmentCredential and the necessary scope for accessing the Microsoft Graph REST API. Then, we initialize a GraphServiceClient object that we will use for our email-related operations.

Next, we move on to the email-sending essence of our service:

EmailService.cs
public async Task SendMessageAsync(
    string sender,
    string recipient,
    string subject,
    string body,
    CancellationToken cancellationToken = default)
{
    var message = new SendMailPostRequestBody
    {
        Message = new Message
        {
            Subject = subject,
            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = body
            },
            ToRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = recipient
                    }
                }
            }
        },
        SaveToSentItems = true
    };

    await _graphClient
        .Users[sender]
        .SendMail
        .PostAsync(message);
}

Inside the method we create a SendMailPostRequestBody object, setting the subject, body content, and recipient's email address. It also specifies the ContentType of our email as HTML. Then we send the message using the PostAsync method of the SendMail endpoint provided by the GraphServiceClient instance. The email is sent on behalf of the specified sender, and the email is saved to the sent items folder.

Note that for the sender, we can also use the unique Azure ID of the user. If you use your credentials to authenticate and want to send the email from your inbox, you can simply replace Users[sender] with Me.

Retrieving Inbox Messages With Microsoft Graph

We can also easily retrieve emails for a given user. First, we need to add a method to our interface:

IEmailService.cs
Task<List<Message>?> GetInboxMessagesAsync(string user);

The GetInboxMessagesAsync method takes in a user parameter that represents the user for whom we want to retrieve the inbox messages. The returned List<Message> will contain the messages present in the user's inbox at the time of the request. If there are no messages, the result will be null.

Then, we implement it:

EmailService.cs
public async Task<List<Message>?> GetInboxMessagesAsync(string user)
{
    var messages = await _graphClient
        .Users[user]
        .Messages
        .GetAsync((request) =>
        {
            request.QueryParameters.Top = 100;
        });

    return messages?.Value;
}

The method utilizes the _graphClient instance we created earlier. Within the method, we make a call to the GetAsync method of the Messages endpoint for the specified user. The request includes a query parameter to retrieve the top 100 messages (by default we get only 10) and store the response in the messages variable. Finally, we return the Value property of the messages, which represents a list of inbox messages. The return type is List<Message>?, which allows us to return null if there are no messages in the inbox.

Retrieving Specific Folder Messages With Microsoft Graph

We can also use Microsoft Graph to retrieve the messages stored in a specific folder:

IEmailService.cs
Task<List<Message>?> GetSpecificFolderMessagesAsync(
    string user,
    string folderName);

We define the GetSpecificFolderMessagesAsync method in our interface and then implement it:

EmailService.cs
public async Task<List<Message>?> GetSpecificFolderMessagesAsync(
    string user,
    string folderName)
{
    var mailFolderResponse = await _graphClient
        .Users[user]
        .MailFolders
        .GetAsync((request) =>
        {
            request.QueryParameters.Filter =
                $"startsWith(displayName, '{folderName}')";
        });

    return mailFolderResponse?.Value?.First()?.Messages;
}

The asynchronous GetSpecificFolderMessagesAsync method takes in two parameters - user, representing the user for whom the folder messages are being retrieved, and folderName, representing the name of the specific folder. Inside the method, we call the GetAsync method of the MailFolders endpoint for the specified user. The request includes a filter parameter to retrieve the mail folder(s) that match the provided folderName using a startsWith filter condition. Then, we check if the Value property of the response is null or not. If not null, we retrieve the first folder from the Value property. Finally, we return the Messages property, which contains the list of messages within the specific folder. The return type of the method is a nullable List<Message>, allowing for the possibility of the folder or messages being null.

Conclusion

Email automation plays a significant role in enhancing productivity and efficiency in our digital communication workflows. By exploring the features of Microsoft Graph, we have uncovered the immense potential for revolutionizing our email communication. From sending emails programmatically to retrieving inbox messages and specific folder messages, Microsoft Graph provides powerful tools for streamlining email automation processes. This is just the tip of the iceberg, so, let's embrace these technologies and embark on a journey of enhanced productivity and streamlined communication.