In this SPFx tutorial, we will discuss how to send an email with attachments using Graph API in SPFx with React JS.
We will create here an SPFx client-side web part and will create a form using React and they will send email using Graph API.
Graph API
Microsoft Graph provides a unified programmability model that you can use to access the tremendous amount of data in Office 365, Windows 10, and Enterprise Mobility + Security, with the entire Microsoft 365 platform.
As we know, Microsoft provided graph API which is more flexible to use in our application. So here I am using Graph API to send an email to other users.
Where you will get Graph API
You can click on this link to redirect graph explorer where we can verify our API and provide the required permission.
Here I am testing my Graph API to confirm this is working fine. Please look into the below screenshot where I am getting some response after running this API.
Sometime we will get permission issues while executing this API. So we have to provide the read/write permission to the specific user.
Below is the screenshot where we will provide permission.
Send email using graph api spfx
Now, we will see how to send email using graph api spfx. For this, first, we will create the SPFx client-side web part.
Step 1: Open Node.js command prompt and create a new project as same as the below screenshot.
Step 2: Here I have created a Web part called SendEmailUsingSPFX and I used React JS as a framework.
So after the execution of the above command, our new web part got created successfully in the solution folder. Now you type code . in the command prompt to open this project in Visual Studio code.
Now you can see the below screenshot where the new web part has been created successfully and the solution look like below.
Step 3: Now we have to follow a few steps to achieve this task.
Open ISendEmailUisngSpfxProp.ts and add the below code.
import {MSGraphClientFactory} from '@microsoft/sp-http';
export interface ISendEmailUsingSpfxProps {
userEmail:string;
graph:MSGraphClientFactory;
}
The Exact code should be looks like as below screenshot.
Step 4: Next go package-solution.json and the below code to give the proper permission to graph API.
Step 5: Next Open SendEmailUsingSpfxWebPart.ts to add the below line of code.
userEmail: this.context.pageContext.user.email,
graph: this.context.msGraphClientFactory
Step 6: Open SendEmailUsingSpfx.tsx and add the below code which will render HTML and execute the graph API.
import * as React from 'react';
import styles from './SendEmailUsingSpfx.module.scss';
import { ISendEmailUsingSpfxProps } from './ISendEmailUsingSpfxProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { MSGraphClient } from '@microsoft/sp-http';
export interface ISendEmailUsingSpfxState{
email:string;
subject: string;
message: string;
files: any[];
blobs: any[];
}
export default class SendEmailUsingSpfx extends React.Component<ISendEmailUsingSpfxProps, ISendEmailUsingSpfxState> {
private reader:FileReader;
constructor(props:ISendEmailUsingSpfxProps){
super(props);
this.reader = new FileReader();
this.state={
email:"",
subject:"",
message:"",
files:null,
blobs:[],
};
this.showUploadedfiles = this.showUploadedfiles.bind(this);
}
public render(): React.ReactElement<ISendEmailUsingSpfxProps> {
console.log(this.state);
return (
<div className={ styles.sendEmailUsingSpfx }>
<div className={ styles.container }>
<div className={ styles.row }>
<span className={ styles.title }>Send Email using Graph API In SharePoint</span>
<br/>
<br/>
<br/>
<input className={styles.subject} type="text" onChange={this.emailHandler.bind(this)} placeholder="To:" value={this.state.email} title="Please enter email address"/>
<br/>
<br/>
<input className={styles.subject} type="text" onChange={this.subjectHandler.bind(this)} placeholder="Subject" value={this.state.subject} title="Subject"/>
<br/>
<br/>
<textarea className={styles.message} rows={6} onChange={this.messageHandler.bind(this)} placeholder={"Message"} value={this.state.message} title="Message"/>
<br/>
<br/>
<div className={styles.inputFileWraper}>
<input
className={styles.inputFile}
type="file"
name="filename"
multiple = {true}
onChange={(file)=>{this.uploadHandler(file);}}
title={"Drag & drop files here"}
/>
</div>
<div>{this.showUploadedfiles()}</div>
<br/>
<button
className={styles.button}
onClick={()=>{this.sendMail();}}
>
Send
</button>
</div>
</div>
</div>
);
}
private emailHandler(e){
this.setState({email:e.target.value});
}
private subjectHandler(e){
this.setState({subject:e.target.value});
}
private messageHandler(e){
this.setState({message:e.target.value});
}
private showUploadedfiles=()=>{
let files = [];
if(this.state.files != null){
for(let i = 0; i < this.state.files.length; i++){
files.push(
<div key={i} className={styles.uploadedFile}>
<span className={styles.uploadedFile1}>{this.state.files[i].name}</span>
<span className={styles.uploadedFile2} >{this.formatBytes(this.state.files[i].size)}</span>
</div>);
}
}
return files;
}
private formatBytes(bytes,decimals=2) {
if(bytes == 0) return '0 Bytes';
var k = 1024,
dm = decimals <= 0 ? 0 : decimals || 2,
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
private uploadHandler(e:any){
this.setState({files:e.target.files});
let files =e.target.files;
for (let i = 0; i < files.length; i++) {
this.attachFile(files[i]);
}
}
private attachFile(file:any):Promise<any>{
this.setState({blobs:[]});
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
resolve(reader.result);
let blobs = this.state.blobs.slice();
let bytes = reader.result.toString().substring(reader.result.toString().indexOf(",") + 1);
blobs.push(bytes);
this.setState({ blobs });
};
});
}
private sendMail(){
const mail = {
message : {
subject: this.state.subject,
body: {
contentType: "Text",
content: this.state.message
},
toRecipients: [
{
emailAddress: {
address: this.state.email
}
}
],
attachments: []
}
};
if(this.state.files != null ){
for (let i = 0; i < this.state.files.length; i++) {
mail.message.attachments.push(
{
"@odata.type": "#microsoft.graph.fileAttachment",
"name": this.state.files[i].name,
"contentBytes": this.state.blobs[i],
"contentType": this.state.files[i].type
}
);
}
}
this.props.graph.getClient().then((client: MSGraphClient) => {
client.api('me/sendMail')
.post(mail)
.then((response) => {
this.setState({
email:"",
subject:"",
message:"",
files:null,
blobs:[],
});
}).catch((ex)=>{
console.log(ex);
alert("Something went wrong! Please try again later.");
});
});
}
}
The page should look like below screenshot.
Step 7: After adding the above code , you can build this web part and check everything is Ok or you found any issue.
You might be facing the CSS issue if you execute this code without adding CSS class. So what we will do, we will open SendEmailUsingSpfx.module.scss and the below class as per the screenshot.
Here I have customized the background color and text color as per customer requirement. So you can change to your own color and theme based on your requirement.
.sendEmailUsingSpfx {
.container {
max-width: 1000px;
margin: 0px auto;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.753), 0 30px 70px 0 rgba(0, 0, 1, 0.1);
}
.row {
@include ms-Grid-row;
@include ms-fontColor-white;
background-color: "[theme: infoBackground, default: #e81123]";
padding: 20px;
}
Deploy the SPFx Web Part
Now we can see how we can deploy the SPFx client side web part to SharePoint Online Office 365.
Once deployed successfully, we can add to a SharePoint Online site and then add the web part to a modern page.
Step 8: Next go to your command prompt and execute this code using below command.
- gulp clean
- gulp build
- gulp serve
- gulp bundle –ship
- gulp package-solution -ship
So you can run the above command as per the order. So once you click on gulp serve, it will open a new page where you have to add your newly added web part.
After adding the new SPFx web part, it will look like the below screenshot.
Step 9: Next what we will do, prepare a package, and upload the package in our SharePoint App Catalog site. So we have to prepare the package using the above command which is in step-8. After creating the package, we have to upload in App catalog site which is the same as the below screenshot.
Step 10: Next go to your SharePoint Online site collection and add the newly created Web part on your page. And test your app, it’s working properly or not. So here I have added my Web Part and I try to send an email to my hotmail email ID.
Grant Graph API permission
Step 11: So before sending an email, make sure the admin approved the Graph API permission in the SharePoint admin center.
Once you add this Web part on your page, It will automatically visible in the admin center as a pending request.
So the admin needs to approve this so that we can able to send an email. Please look into the screenshot where my admin has approved my request.
Step 12: Once I click on Send button, I received an email in my hotmail which is came from onMicrosoft.com domain.
You can look into the below screenshot where I received an email with an attachment.
In this tutorial, we learned how to send email using graph api spfx, particularly, we discussed how to send an email with attachments using Graph API in the SPFx web part with react js. Please try this and put your comment, if you are facing any issue.
If you are new to SharePoint Framework development, you can check out the below tutorials:
- Create a Hello World WebPart in SharePoint using SPFX
- How to create a New SPFx Web part in an existing project in SharePoint
- How to get user details using Microsoft Graph API in SPFx
- How to get user outlook messages using Microsoft graph api in SPFx with React JS
- How to display SharePoint list items in a table using SPFX
- How to use bootstrap in SPFx webpart
- SPFx – Bind dropdown list from SharePoint list using PnP
Rajkiran is currently working as a SharePoint Consultant in India . Rajkiran having 7+ years of experience in Microsoft Technologies such as SharePoint 2019/2016/2013/2010, MOSS 2007,WSS 3.0, Migration, Asp.Net, C#.Net, Sql Server, Ajax, jQuery etc.He is C#Corner MVP (2 Times).
Thank you this is great
How would you get files from SharePoint library to attach?
This method only works with small files unfortunately.
Any tutorial on how to send emails with attachments with more then 3Mb?