How to Send Emails Using Microsoft Graph API

Prathamesh Kulkarni
Another Integration Blog
6 min readJun 8, 2022

In this article, I will demonstrate how to send emails using Microsoft Graph API. Usually, we send emails with the help of an email connector, for which we need a username and password. To avoid this, Microsoft Graph API has a provision to send emails with the help of an 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.

First, you will need an account with Azure and the application. To allow our applications to send e-mails as a given user or service account, we need to configure an Azure AD application with the appropriate permission. Additionally, we need to ensure that the user or service account has a license assigned for sending e-mails. At this point, we can begin to build our code.

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

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

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

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

To create a new application, click on this highlighted application number.

I have created a test application. Now, you will need to get your client secret using the following step:

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

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 will need them in the future. You can find these on the ‘Overview’ page of your app, which you can see in the first image.

Set up Permissions

From the app page in the Azure Portal, choose:

  • API permissions > Add a permission
  • Microsoft Graph > Application Permissions > Mail.Send > Add Permission

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

Use application permissions if you want to allow emails to be sent by any user in the organization.

Select ‘Mail.send’ as shown in the image below.

Your configured permissions should look something like this.

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

  • New Azure AD application
  • Configured the appropriate permissions for sending e-mails
  • Ensured there was a license assigned to the user account

With that, we’re ready to build the application in Mule 4.

Building the Application

For this, we need two requestors.

1. Fetch token using the client credentials

2. Send an email using the fetched token

This is the overall structure of the application:

As mentioned, the first step is to fetch the token.

The required format is given below. It should be in the format: x-www-form-urlencoded.

In the next step, you will 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 will need it in 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 for to send an email.

Cc recipients and attachments are optional. You can send any type of message in the body by giving the content type in the attachment, and indicating which format you want the output to be. You can also specify this in MIME-TYPE, like application/json.

You can have multiple addresses as well which will be an array of email-address objects.

Now, configure the Requestor to sendEmail.

Use the URL POST https://graph.microsoft.com/v1.0/me/sendMail and send the Bearer Token in the headers section.

Run Application

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

The application ran successfully. Check the inbox to confirm that the email was delivered.

Tadddaa… we got the email!

The email contains the body with an attachment.

Pasting 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>

Now you should be able to successfully send an email with Microsoft Graph API.

--

--