Fetch Email from shared mailboxes in SPFx webpart

In this article, I have explained how to fetch the shared mailbox emails in office 365 tenant with the help of Microsoft Graph API.

Endpoint: https://graph.microsoft.com/v1.0/users/{email | userid }/messages

Permission Scope: Mail.Read.Shared, User.Read.All

I have already created a new SPFx solution named “MSGraph-SharedMailBoxAccess” with “No Javascript framework” template

Open the “package-solution.json” under config folder inside your solution to include the above permission scopes

"webApiPermissionRequests": [     
      {
        "resource": "Microsoft Graph",
        "scope": "User.Read.All"
      },
      {
        "resource": "Microsoft Graph",
        "scope": "Mail.Read.Shared"
      }
]

Next step am using @pnp/Graph library to send the graph API requests

Install PNP Graph using the below npm

npm install @pnp/graph

After successful installation of NPM Package under src -> webparts -> Open “SharedMailBoxWebPart.ts”

Import graph library from installed package

 import { graph } from '@pnp/graph';
 import '@pnp/graph/users';
 import '@pnp/graph/messages'

Add onInit() Method to initialize the Graph API configuration for SPFx

public onInit(): Promise<void> {
    return super.onInit().then(_ => {
      graph.setup({
        spfxContext: this.context
      })
    })
  }

Create function “GetSharedMailBox()” to send API request to retrieve all the emails from your shared mail box

public GetSharedMailBox() {
var sharedMailBoxUserID = "fc9143b4-ee46-45bf-934a-4e1f340337bb";
graph.users.getById(sharedMailBoxUserID).messages.get().then(items => {		
		if (items.length > 0) {
			console.log("items", items)
		})
}
else {
	console.log("items", items)
}
}).catch(error => {
	console.log(error)
})
}

Let me do some changes in HTML to display the email messages with help of semantic UI

Full code:

import { Version } from '@microsoft/sp-core-library';
import { graph } from '@pnp/graph';
import '@pnp/graph/users';
import '@pnp/graph/messages'
//import '@pnp/graph/presets/all'
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import { SPComponentLoader } from '@microsoft/sp-loader';

import * as strings from 'SharedMailBoxWebPartStrings';
import { PnPClientStorage } from '@pnp/common';

//load the css from CDN for semantic ui
SPComponentLoader.loadCss("https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css");

export interface ISharedMailBoxWebPartProps {
  description: string;
}

export default class SharedMailBoxWebPart extends BaseClientSideWebPart<ISharedMailBoxWebPartProps> {

  public onInit(): Promise<void> {
    return super.onInit().then(_ => {
      graph.setup({
        spfxContext: this.context
      })
    })
  }

  public render(): void {
    this.domElement.innerHTML = `
    <div class="ui cards">
    </div> `

    //Trigger the API Request to retreive emails from shared mail box
    this.GetSharedMailBox();
  }

  public GetSharedMailBox() {
    var sharedMailBoxUserID = "fc9143b4-ee46-45bf-934a-4e1f340337bb";
    graph.users.getById(sharedMailBoxUserID).messages.get().then(items => {
      var html = "";
      if (items.length > 0) {
        console.log("items", items)
        items.forEach(response => {
          html += `<div class="card">
          <div class="content">
            <div class="header">${response.sender.emailAddress.address}</div>
            <div class="meta">${response.sender.emailAddress.name}</div>
            <div class="description">
              ${response.body.content}
            </div>
          </div>
        </div>`

        })
      } else {
        html += `<div class="card">
           <div class="content">
             <div class="description">
               ${"Empty Mail Box"}
             </div>
           </div>
         </div>`
      }
      document.getElementsByClassName('ui cards')[0].innerHTML = html;
    }).catch(error => {
      console.log(error)
    })
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

After all done package the solution using below command

  • gulp clean
  • gulp build
  • gulp bundle –ship
  • gulp package-solution –ship

Once package completed open the folder named “sharepoint” inside your SPFx solution from the explorer view

Now login to your sharepoint admin center open your app catalog site and upload the solution. once solution uploaded successfully navigate to “API access” in sharepoint admin center

Approve the permission under pending requests important thing you need a global administrator privileges to approve web API scopes

It’s look like on successful approval

Now open your sharepoint site and add the SPFx webpart wherever your want

I have already have 2 mails in my shared mail box see how it look like below

Keep Sharing!…..

Author Profile

Vinodh
Vinodh is a Microsoft MVP for SharePoint (Office Apps and Services) having 5+ years of experience in Microsoft Technologies.

His interest and expertise includes SharePoint Online Development, PowerApps Development, Flows for SharePoint and PowerApps. Single Page Apps/Add ins for SharePoint using React, Angular. SharePoint Farm Management, 2, 3 and upto 6 tier SharePoint Farm Installation and Configuration.

Awards :
Microsoft Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
C# Corner Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
Technology Expertise :
SharePoint Online, SharePoint 2013, SharePoint 2016 and SharePoint 2019 Preview.
Intranets both Modern and Classic, SharePoint Frameworks Customisation, SharePoint Add-ins, SharePoint single page apps.
Angular 5 with Bootstrap single page apps.
Typescript, JQuery and Javascript.
Micrsoft Flow and Powerapps.
Utilised :
Microsoft Graph API, SharePoint REST, SharePoint PnP JS.
Out of Box :
Consume Content search web parts for internet publishing sites using custom display templates.
Having knowledge on SharePoint workflows and SharePoint Designer workflows.
List customisation using JS Link, JSON Formatting.
Having knowledge in Active directory management services.
Create and configure service applications in SharePoint (MMS, UPSA, SSA).
Configure Outgoing email settings using SMTP Services.

Add a Comment

Your email address will not be published. Required fields are marked *