Fetch Email from Shared Mailboxes in SPFx WebPart

Introduction 

 
In this article, I explain 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 the “No Javascript framework” template.
 
Open the “package-solution.json” under config folder inside your solution to include the above permission scopes
  1. "webApiPermissionRequests": [       
  2.       {  
  3.         "resource""Microsoft Graph",  
  4.         "scope""User.Read.All"  
  5.       },  
  6.       {  
  7.         "resource""Microsoft Graph",  
  8.         "scope""Mail.Read.Shared"  
  9.       }  
  10. ]  
Next, I am using @pnp/Graph library to send the graph API requests.
 
Install PNP Graph using the below npm:
  1. npm install @pnp/graph  
After successful installation of NPM Package under src -> webparts -> Open “SharedMailBoxWebPart.ts”
 
Import the graph library from the installed package.
  1. import { graph } from '@pnp/graph';  
  2. import '@pnp/graph/users';  
  3. import '@pnp/graph/messages'  
Add onInit() Method to initialize the Graph API configuration for SPFx.
  1. public onInit(): Promise<void> {  
  2.     return super.onInit().then(_ => {  
  3.       graph.setup({  
  4.         spfxContext: this.context  
  5.       })  
  6.     })  
  7.   }  
Create the function “GetSharedMailBox()” to send an API request to retrieve all emails from your shared mailox. 
  1. public GetSharedMailBox() {  
  2. var sharedMailBoxUserID = "fc9143b4-ee46-45bf-934a-4e1f340337bb";  
  3. graph.users.getById(sharedMailBoxUserID).messages.get().then(items => {        
  4.         if (items.length > 0) {  
  5.             console.log("items", items)  
  6.         })  
  7. }  
  8. else {  
  9.     console.log("items", items)  
  10. }  
  11. }).catch(error => {  
  12.     console.log(error)  
  13. })  
  14. }  
Let me do some changes in HTML to display the email messages with help of semantic UI.
 
Full code
  1. import { Version } from '@microsoft/sp-core-library';  
  2. import { graph } from '@pnp/graph';  
  3. import '@pnp/graph/users';  
  4. import '@pnp/graph/messages'  
  5. //import '@pnp/graph/presets/all'  
  6. import {  
  7.   BaseClientSideWebPart,  
  8.   IPropertyPaneConfiguration,  
  9.   PropertyPaneTextField  
  10. } from '@microsoft/sp-webpart-base';  
  11. import { escape } from '@microsoft/sp-lodash-subset';  
  12. import { SPComponentLoader } from '@microsoft/sp-loader';  
  13.   
  14. import * as strings from 'SharedMailBoxWebPartStrings';  
  15. import { PnPClientStorage } from '@pnp/common';  
  16.   
  17. //load the css from CDN for semantic ui  
  18. SPComponentLoader.loadCss("https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css");  
  19.   
  20. export interface ISharedMailBoxWebPartProps {  
  21.   description: string;  
  22. }  
  23.   
  24. export default class SharedMailBoxWebPart extends BaseClientSideWebPart<ISharedMailBoxWebPartProps> {  
  25.   
  26.   public onInit(): Promise<void> {  
  27.     return super.onInit().then(_ => {  
  28.       graph.setup({  
  29.         spfxContext: this.context  
  30.       })  
  31.     })  
  32.   }  
  33.   
  34.   public render(): void {  
  35.     this.domElement.innerHTML = `  
  36.     <div class="ui cards">  
  37.     </div> `  
  38.   
  39.     //Trigger the API Request to retreive emails from shared mail box  
  40.     this.GetSharedMailBox();  
  41.   }  
  42.   
  43.   public GetSharedMailBox() {  
  44.     var sharedMailBoxUserID = "fc9143b4-ee46-45bf-934a-4e1f340337bb";  
  45.     graph.users.getById(sharedMailBoxUserID).messages.get().then(items => {  
  46.       var html = "";  
  47.       if (items.length > 0) {  
  48.         console.log("items", items)  
  49.         items.forEach(response => {  
  50.           html += `<div class="card">  
  51.           <div class="content">  
  52.             <div class="header">${response.sender.emailAddress.address}</div>  
  53.             <div class="meta">${response.sender.emailAddress.name}</div>  
  54.             <div class="description">  
  55.               ${response.body.content}  
  56.             </div>  
  57.           </div>  
  58.         </div>`  
  59.   
  60.         })  
  61.       } else {  
  62.         html += `<div class="card">  
  63.            <div class="content">  
  64.              <div class="description">  
  65.                ${"Empty Mail Box"}  
  66.              </div>  
  67.            </div>  
  68.          </div>`  
  69.       }  
  70.       document.getElementsByClassName('ui cards')[0].innerHTML = html;  
  71.     }).catch(error => {  
  72.       console.log(error)  
  73.     })  
  74.   }  
  75.   
  76.   protected get dataVersion(): Version {  
  77.     return Version.parse('1.0');  
  78.   }  
  79.   
  80.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  81.     return {  
  82.       pages: [  
  83.         {  
  84.           header: {  
  85.             description: strings.PropertyPaneDescription  
  86.           },  
  87.           groups: [  
  88.             {  
  89.               groupName: strings.BasicGroupName,  
  90.               groupFields: [  
  91.                 PropertyPaneTextField('description', {  
  92.                   label: strings.DescriptionFieldLabel  
  93.                 })  
  94.               ]  
  95.             }  
  96.           ]  
  97.         }  
  98.       ]  
  99.     };  
  100.   }  
  101. }  
Once finished packaging the solution, use the below command:
  • gulp clean
  • gulp build
  • gulp bundle –ship
  • gulp package-solution –ship
Once the package is completed, open the folder “sharepoint” inside your SPFx solution from the explorer view.
 
Fetch Email From Shared Mailboxes In Spfx WebPart
 
Fetch Email From Shared Mailboxes In Spfx WebPart
 
Now, login to your Sharepoint admin center and open your app catalog site, then upload the solution. Once the solution has uploaded successfully, navigate to “API access” in the Sharepoint admin center.
 
Fetch Email From Shared Mailboxes In Spfx WebPart
 
Approve the permission under pending requests.
 
Note: You need a global administrator privileges to approve web API scopes.
 
Fetch Email From Shared Mailboxes In Spfx WebPart
 
Now open your SharePoint site and add the SPFx webpart wherever you want.
 
I already had 2 emails in my shared mailbox, see how it looked below:
 
Fetch Email From Shared Mailboxes In Spfx WebPart
 
Keep Sharing!