How to send email using Microsoft Graph API

  • June 07, 2022

In this article, we’re going to see how to send emails using Microsoft Graph Application Programming Interface (API). Usually, we send emails with the help of an email connector. For that, we need a user name and password. To avoid this, Microsoft Graph API has a provision to send emails with the help of API.

What is Microsoft Graph API?

Microsoft Graph is a RESTful web API that enables you to access Microsoft Cloud service resources. After you register your app and get authentication tokens for a user or service, you can make requests to the Microsoft Graph API.

To use this service, you’ll need an account with Azure and the application.

  • How to do the setup in Azure
    • Create an Azure Active Directory (AD) app with Microsoft Graph permissions
    • Make sure the account is licensed to send emails.
    • Build the code

To allow our applications to send emails as a given user or service account, we need to configure an Azure AD application with the appropriate permissions. Additionally, we need to ensure that the user or service account has a license assigned for sending emails.

The process of configuring our Azure AD apps and users is simple and easy.

Create an Azure Active Directory Application

  • Azure Portal > Active Directory > App registrations > New registration
  • Name: Whatever you want
  • Type: Accounts in this organizational directory only (Single-tenant)
  • Redirect URI: Not required

Microsoft Graph can support both the traditional ClientID + ClientSecret approach, as well as the Managed Identity approach. Here I’m using ClientID + ClientSecret approach\

We then create a new secret and securely store the value of the said secret, along with the Tenant ID and the app’s Client ID.

Click on this highlighted application number. You can create a new application there.

I’ve already created a test application.

  • Certificates & Secrets > New client secret
  • Copy the secret and store it in a safe location so you can use it again.

Next, make sure you copy the Application ID (Client ID) and the Tenant ID for your application and place them in a safe location, as you’ll need them in the future. You can find these on the overview page of your app.

Set up permissions

Now is the time to set up permissions.

From the app page in the Azure Portal:

API permissions > Add a permission

Microsoft Graph > Application Permissions > Mail.Send > click Add Permission

Use delegated permissions if you want a user to consent to the app explicitly, and allow that one user to send emails from the application.

Use application permissions if you want to allow sending emails as any user in the organization.

select Mail.send.

We’re done with the preparations. At this point, we should have:

  • A new Azure AD application
  • Configured the appropriate permissions for sending emails
  • Ensured there was a license assigned to the user account

We’re ready to build the application in Mule 4.

Building the application

We need two requestors to:

  • Fetch token with the help of client credentials
  • Send an email with the help of fetched token

This is the structure of the application.

The first step is to fetch the token.

The necessary format is given below. It should also be in x-www-form-urlencoded.

In the next step, you’ll need your Tenant ID to request the token.

The Tenant ID is part of the URL, which is masked.

Once you get the token, store it in a variable because we’ll need it in the future.

Now it’s time to create a message body with an attachment. To send the attachment, you need to convert your payload into base64 format.

This is the required payload to send email.

CC recipients is optional. Attachment is also optional. You can send any type of message in the body by giving content type. Format the attachment in which format you want output. You can specify in MIME-TYPE as application/json.

You can have multiple addresses, which will be an array of email address objects.

Now, configure the Requestor to sendEmail.

The URL used is POST https://graph.microsoft.com/v1.0/me/sendMail and send Bearer Token in the header section.

Run application

It’s time to run the application and test it.

The application ran successfully. Time to check your inbox. We got the email body with an attachment.

Here’s the code for reference.

XML

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:email="http://www.mulesoft.org/schema/mule/email" xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"

xmlns:http="http://www.mulesoft.org/schema/mule/http"

xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd

http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd

http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd

http://www.mulesoft.org/schema/mule/email http://www.mulesoft.org/schema/mule/email/current/mule-email.xsd">

<http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="12efcb11-2560-475d-9c43-f1121237d700" >

<http:listener-connection host="0.0.0.0" port="8081" />

</http:listener-config>

<http:request-config name="HTTP_Request_configuration_Send_Email" doc:name="HTTP Request configuration" doc:id="b79ac069-6cfa-4e0d-bd05-d8d7f39745e1" >

<http:request-connection host="graph.microsoft.com" protocol="HTTPS"/>

</http:request-config>

<http:request-config name="HTTP_Request_configuration_Token" doc:name="HTTP Request configuration" doc:id="0809b1a9-73b7-4c16-904e-83b502df0687" >

<http:request-connection protocol="HTTPS" host="login.microsoftonline.com" />

</http:request-config>

<flow name="send-email-graph-api-code" doc:id="bd3b54f7-a9bd-4fc6-91d9-353177cb942b" >

<http:listener doc:name="Listener" doc:id="10800bec-5217-4b31-a461-9c3e48e6bd43" config-ref="HTTP_Listener_config" path="/testEmail"/>

<ee:transform doc:name="Set Client Cred to fetch token" doc:id="732271f2-0ad8-4da9-a0c8-6fe736b45c18" >

<ee:message >

<ee:set-payload ><![CDATA[%dw 2.0

output application/x-www-form-urlencoded

---

{

"client_secret" : "app_client_secret",

"scope" : "https://graph.microsoft.com/.default",

"grant_type" : "client_credentials",

"client_id" : "app_client_id"

}]]></ee:set-payload>

</ee:message>

</ee:transform>

<http:request method="POST" doc:name="Request To Fetch Token" doc:id="14b64477-75d0-4094-988e-55c35dfa749d" config-ref="HTTP_Request_configuration_Token" path="/{Tenant_ID}/oauth2/v2.0/token" target="bearerToken">

<http:headers ><![CDATA[#[output application/java

---

{

"Content-Type" : "application/x-www-form-urlencoded"

}]]]></http:headers>

</http:request>

<ee:transform doc:name="Create attachement payload" doc:id="b068276c-2598-4a70-99e8-d3d731c59c84" >

<ee:message >

</ee:message>

<ee:variables >

<ee:set-variable variableName="attachment" ><![CDATA[%dw 2.0

output application/json

---

{

"Name" : "Prathamesh Kulkarni"

}]]></ee:set-variable>

</ee:variables>

</ee:transform>

<ee:transform doc:name="Create Request Body For Send Email" doc:id="8f69879d-b804-40fc-b8f0-7431aaf123d4" >

<ee:message >

<ee:set-payload ><![CDATA[%dw 2.0

output application/json

import toBase64 from dw::core::Binaries

---

{

  "message": {

    "subject": "This is test mail for Demo",

    "body": {

      "contentType": "Html",

      "content": "<!DOCTYPE html>

<html>

<body>

<h1>This is Demo 1</h1>

</body>

</html>"    },

    "toRecipients": [

      {

        "emailAddress": {

          "address": "youremail.com"

        }

      }

    ],

   "ccRecipients": [

      {

        "emailAddress": {

          "address": "youremail.com"

        }

      }

    ],

     "attachments": [

      {

        "@odata.type": "#microsoft.graph.fileAttachment",

        "name": "test.json",

        "contentType": "application/json",

        "contentBytes": toBase64(write(vars.attachment,"application/json"))

      }

    ]

},

  "saveToSentItems": "false"

}]]></ee:set-payload>

</ee:message>

</ee:transform>

<http:request method="POST" doc:name="Request to Send Email" doc:id="8e04b0a1-9c73-4715-8b4f-8146ec81f10b" config-ref="HTTP_Request_configuration_Send_Email" path="/v1.0/users/{email.domain.com}/sendMail">

<http:headers ><![CDATA[#[output application/java

---

{

"Authorization" : vars.bearerToken.access_token,

"Content-type" : "application/json"

}]]]></http:headers>

</http:request>

<logger level="INFO" doc:name="Log-Flow End" doc:id="13e07383-cafb-4f41-855d-4a398722cbdf" message="Flow End"/>

</flow>

</mule>

— By Prathamesh P. Kulkarni