FETCH EMAIL FROM SHARED MAILBOXES IN SPFX WEBPART

Vinodh
 
SharePoint MVP
April 17, 2020
 
Rate this article
 
Views
604

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

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 Info

Vinodh
 
SharePoint MVP
 
Rate this article
 
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 ...read more
 

Leave a comment