Getting started with Microsoft Graph API in a Xamarin Forms Application

Introduction

Microsoft offers a different service in the Cloud, Mail, Calendar, Contact, Chat and files from the common Microsoft portal, and also if you want to integrate with your application, you can access unified API wrappers in the Microsoft graph SDK. In this article you will learn how to implement login authentication and send mail using Microsoft graph API in the Xamarin Forms application.

Xamarin

Prerequisites

  1. Download and install Visual 2017 Community Edition or higher.
  2. Create Microsoft Account (If you have already registered a Microsoft account, it’s not required)

Getting Started Creating An Application

Step 1

You can navigate  to the following URL https://developer.microsoft.com/en-us/graph/quick-start for register app and create a sample app.

Step 2

Select the platform and Microsoft will create a simple app that connects to Office 365 and calls the Microsoft Graph API.

Xamarin

Step 3 Register APP ID

You can register the application using click on “Get an app ID” and it will navigate to Microsoft application registration portal where you will be able to get an App ID and redirect URL. You will need either a School / Work /corporate / Azure AD or Microsoft account.

Xamarin

Step 4 Registration Success

After logging in with your Microsoft account and waiting for few seconds appid and redirect url will generate automatically. If you want to modify or manage your app, you can click on application registration portal .

Xamarin

Step 5 Manage App in Registration Portal

You can manage or edit application from portal in the following App Name, redirect URL, generate new password, application logo, update the permission and click on Save button.

Xamarin

Step 6 Download Sample Code

You can download and unzip the source code > open the source code using Visual Studio. The Sample application has multiple platform support such as iOS, Android, and UWP. The code sample will introduce you to authentication and send an email from your account.

Xamarin

Step 7 Microsoft Graph Client Library

Microsoft Graph Client Library allows you to call Office 365, Azure AD and other Microsoft services through a single unified developer experience so right click on your solution and verify the below NuGet package is installed in the solution.

Xamarin

Step 8 Configure the project

Open the App.cs file from XamarinConnect PCL project > replace your client ID and add the user permission scope.

  1. public static string ClientID = "< Update your Client ID > ";  
  2. public static PublicClientApplication IdentityClientApp = new PublicClientApplication(ClientID);  
  3. public static string[] Scopes = { "User.Read""Mail.Send""Files.ReadWrite" };  

 

Step 9 Configure Send mail

Open the MainHelper.cs from XamarinConnect PCL project > update ComposeAndSendMailAsync method as per your requirement

  1. public async Task ComposeAndSendMailAsync(string subject, string bodyContent, string recipients) {  
  2.     // Get current user photo  
  3.     Stream photoStream = await GetCurrentUserPhotoStreamAsync();  
  4.     // If the user doesn't have a photo, or if the user account is MSA, we use a default photo  
  5.     if (photoStream == null) {  
  6.         var assembly = typeof(MailHelper).GetTypeInfo().Assembly;  
  7.         photoStream = assembly.GetManifestResourceStream("XamarinConnect.test.jpg");  
  8.     }  
  9.     MemoryStream photoStreamMS = new MemoryStream();  
  10.     // Copy stream to MemoryStream object so that it can be converted to byte array.  
  11.     CopyTo(photoStreamMS);  
  12.     DriveItem photoFile = await UploadFileToOneDriveAsync(photoStreamMS.ToArray());  
  13.     MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();  
  14.     Add(new FileAttachment {  
  15.         ODataType = "#microsoft.graph.fileAttachment",  
  16.             ContentBytes = photoStreamMS.ToArray(),  
  17.             ContentType = "image/png",  
  18.             Name = "me.png"  
  19.     });  
  20.     // Get the sharing link and insert it into the message body.  
  21.     Permission sharingLink = await GetSharingLinkAsync(photoFile.Id);  
  22.     string bodyContentWithSharingLink = String.Format(bodyContent, sharingLink.Link.WebUrl);  
  23.     // Prepare the recipient list  
  24.     string[] splitter = {  
  25.         ";"  
  26.     };  
  27.     var splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);  
  28.     List < Recipient > recipientList = new List < Recipient > ();  
  29.     foreach(string recipient in splitRecipientsString) {  
  30.         Add(new Recipient {  
  31.             EmailAddress = new EmailAddress {  
  32.                 Address = recipient.Trim()  
  33.             }  
  34.         });  
  35.     }  
  36.     try {  
  37.         var graphClient = AuthenticationHelper.GetAuthenticatedClient();  
  38.         var email = new Message {  
  39.             Body = new ItemBody {  
  40.                     Content = bodyContentWithSharingLink,  
  41.                         ContentType = BodyType.Html,  
  42.                 },  
  43.                 Subject = subject,  
  44.                 ToRecipients = recipientList,  
  45.                 Attachments = attachments  
  46.         };  
  47.         try {  
  48.             await graphClient.Me.SendMail(email, true).Request().PostAsync();  
  49.         } catch (ServiceException exception) {  
  50.             throw new Exception("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);  
  51.         }  
  52.     } catch (Exception e) {  
  53.         throw new Exception("We could not send the message: " + e.Message);  
  54.     }  
  55. }  

 

Step 10 Run the Application

  1. Select iOS, android and Windows project and run the application .
  2. Click on Connect Button from iOS/Android /Windows

    Xamarin

  3. Sign in with your personal or work or school account and grant the requested permissions.

    Xamarin
    Xamarin

  4. Click on Send mailbutton. When the mail is sent, a Success message is displayed.
    Xamarin

This mail message includes the photo as an attachment and also provides a sharing link to the uploaded file in OneDrive. Check your mail from Inbox or Spam.

Xamarin

Summary

In this article, you learned about how to implement login authentication and send mail using Microsoft graph API in the Xamarin Forms application.

If you have any questions/ feedback/ issues, please write in the comment box.

Next Recommended Readings