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.
Prerequisites
- Download and install Visual 2017 Community Edition or higher.
- 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.
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.
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 .
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.
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.
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.
Step 8 Configure the project
Open the App.cs file from XamarinConnect PCL project > replace your client ID and add the user permission scope.
- public static string ClientID = "< Update your Client ID > ";
- public static PublicClientApplication IdentityClientApp = new PublicClientApplication(ClientID);
- 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
- public async Task ComposeAndSendMailAsync(string subject, string bodyContent, string recipients) {
-
- Stream photoStream = await GetCurrentUserPhotoStreamAsync();
-
- if (photoStream == null) {
- var assembly = typeof(MailHelper).GetTypeInfo().Assembly;
- photoStream = assembly.GetManifestResourceStream("XamarinConnect.test.jpg");
- }
- MemoryStream photoStreamMS = new MemoryStream();
-
- CopyTo(photoStreamMS);
- DriveItem photoFile = await UploadFileToOneDriveAsync(photoStreamMS.ToArray());
- MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();
- Add(new FileAttachment {
- ODataType = "#microsoft.graph.fileAttachment",
- ContentBytes = photoStreamMS.ToArray(),
- ContentType = "image/png",
- Name = "me.png"
- });
-
- Permission sharingLink = await GetSharingLinkAsync(photoFile.Id);
- string bodyContentWithSharingLink = String.Format(bodyContent, sharingLink.Link.WebUrl);
-
- string[] splitter = {
- ";"
- };
- var splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
- List < Recipient > recipientList = new List < Recipient > ();
- foreach(string recipient in splitRecipientsString) {
- Add(new Recipient {
- EmailAddress = new EmailAddress {
- Address = recipient.Trim()
- }
- });
- }
- try {
- var graphClient = AuthenticationHelper.GetAuthenticatedClient();
- var email = new Message {
- Body = new ItemBody {
- Content = bodyContentWithSharingLink,
- ContentType = BodyType.Html,
- },
- Subject = subject,
- ToRecipients = recipientList,
- Attachments = attachments
- };
- try {
- await graphClient.Me.SendMail(email, true).Request().PostAsync();
- } catch (ServiceException exception) {
- throw new Exception("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);
- }
- } catch (Exception e) {
- throw new Exception("We could not send the message: " + e.Message);
- }
- }
Step 10 Run the Application
- Select iOS, android and Windows project and run the application .
- Click on Connect Button from iOS/Android /Windows
- Sign in with your personal or work or school account and grant the requested permissions.
- Click on Send mailbutton. When the mail is sent, a Success message is displayed.
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.
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.