Send Email Using Microsoft Graph API From SharePoint Online

In my previous article, I explained how to fetch access token to consume Graph API. In this article, we will discuss how to send an email from SharePoint using Microsoft Graph API. You can read the previous part here.
HTTP Request
  • POST https://graph.microsoft.com/v1.0/{userid | userprincipalname}/sendMail
  • POST https://graph.microsoft.com/v1.0/me/sendMail
The above HTTP requests help in sending the email.
 
Let's open Microsoft Graph Explorer and send a test message to my personal email.
 
Navigate to:

https://developer.microsoft.com/en-us/graph/graph-explorer 
 
Log in to your Office 365 work or school account.
 
In Graph Explorer, navigate to Outlook Mail section where there are plenty of HTTP requests with different activities.
 
SharePoint
 
Now, I am using POST request for sending an email to my personal Gmail account with the help of Graph API.
 
Click on "Send an email".
 
Request Header - Content-Type - application/json 
 
Request Body  in JSON format -
  1. {  
  2.     "message": {  
  3.         "subject""Test Message from Microsoft Graph Explorer",  
  4.         "body": {  
  5.             "contentType""Text",  
  6.             "content""This is the test email body message from microsoft graph api"  
  7.         },  
  8.         "toRecipients": [{  
  9.             "emailAddress": {  
  10.                 "address""[email protected]"  
  11.             }  
  12.         }]  
  13.     }  
  14. }   
SharePoint
 
Click "Run Query".
 
The request is successful. You are able to see the below message from the Graph Explorer.
 SharePoint

So now, I am going to open my email inbox to check if the mail has been sent from Microsoft Graph API Explorer.
 
SharePoint 
 
So, in the next step, I am going to send the HTTP Request from jquery AJAX. Open SharePoint and create an HTML form for sending an email.
 
HTML Code
  1. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  2.   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  
  3.   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  4. <body>  
  5. <div class="container">  
  6. <div class="form-group">  
  7.     <label for="email">To:</label>  
  8.     <input type="email" class="form-control" id="email" required>  
  9.   </div>  
  10.   <div class="form-group">  
  11.     <label for="txtsubject">Subject:</label>  
  12.     <input type="text" class="form-control" id="txtsubject" required>  
  13.   </div>  
  14.    <div class="form-group">  
  15.     <label for="txtmessage">Message:</label>  
  16.     <textarea class="form-control" id="txtmessage" rows="7" required></textarea>  
  17.   </div>  
  18.   <button type="submit" onclick="sendEmail();" class="btn btn-default">Send</button>  
  19.   </div>     
  20. </body>  
Now, the design looks like the below screen.
 
SharePoint 
Now, create a function requesttoken() to fetch the access token using OAuth.
  
Code 
  1. function requestToken() {  
  2.   
  3.         $.ajax({  
  4.             "async"true,  
  5.             "crossDomain"true,  
  6.             "url""https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie    
  7.             "method""POST",  
  8.             "headers": {  
  9.                 "content-type""application/x-www-form-urlencoded"  
  10.             },  
  11.             "data": {  
  12.              "grant_type""client_credentials",    
  13.             "client_id ""8baf0301-27df-44b1-b4fe-7911b9a918de"//Provide your app id    
  14.             "client_secret""DxSF1K+JKl7LWJK8+3Ibg4il5JM4qUvdwOtShsYNvEA="//Provide your secret    
  15.             "scope ""https://graph.microsoft.com/.default"  
  16.             },  
  17.             success: function(response) {  
  18.                 console.log(response);  
  19.                 token = response.access_token;  
  20.               },  
  21.             error: function(error) {  
  22.             console.log(JSON.stringify(error));  
  23.            }  
  24.         })  
  25.     }  
Call the requesttoken() function in onload jQuery document ready function.
  1. var token;   // Globally created variable holds the access token 
  2. $(document).ready(function() {  
  3.            requestToken();  
  4.    });  
Just go to the console and see the reponse of AJAX request.
 
SharePoint 
 
Let's create a function sendEmail() to send email to the user.
 
Pass "message" property in the request body.
  1. function sendEmail() {  
  2.   //Variable to get values from input elements
  3.     var to = $('#email').val();  
  4.     var sub = $('#txtsubject').val();  
  5.     var msg = $('#txtmessage').val();  
  6.   
  7.     $.ajax({  
  8.         "async"true,  
  9.         "crossDomain"true,  
  10.         "url""https://graph.microsoft.com/v1.0/users/[email protected]/sendMail",  
  11.         "method""POST",  
  12.         "headers": {  
  13.             "authorization""Bearer" + token,       //Pass the token to authorize the API request
  14.             "content-type""application/json"  
  15.         },  
  16.         "processData"false,  
  17.         "data": JSON.stringify({                    // Pass JSON data with message property
  18.             "message": {  
  19.                 "subject": sub,  
  20.                 "body": {  
  21.                     "contentType""Text",    // Body Content Type will be text or HTML
  22.                     "content": msg  
  23.                 },  
  24.                 "toRecipients": [{  
  25.                     "emailAddress": {  
  26.                         "address": to  
  27.                     }  
  28.                 }]  
  29.             }  
  30.         }),  
  31.         success: function(response) {  
  32.             alert("email sent successfully to " + to + "");  
  33.   
  34.         },  
  35.         error: function(error) {  
  36.             console.log(JSON.stringify(error));  
  37.         }  
  38.     })  
  39. }  
So, let's compose a message to send email from SharePoint.

SharePoint 
Click Send and you are able to see the alert email has been sent successfully.
 
SharePoint 
Now, am going to open my mailbox to check if the mail I have sent is received or not.
 
Hurray!
 
The email has been received.
 
SharePoint 
 SharePoint
 
In my upcoming article, we will discuss more things using Microsoft Graph API. 
 
Happy SharePointing!