Send Email from SharePoint using JSOM

Send Email from JSOM.jpg

To send emails from SharePoint, we use SharePoint workflow or SharePoint Utility Email using C#. But what if you want to send emails from your client-side code.

So, recently I faced a situation where I have to send emails from my client-side code where I was using JSOM as CEWP mythology. So, I was looking for a way where I found “SP.Utilities.Utility.SendEmail” in my searches. And it is really a very simple way to send email. But there is only one catch on which we have to be concerned as the email recipient(s) have to be the users who have visited the site. Any email accounts that have not been authenticated to SharePoint will throw an error.

Here is the code given bellow:


var sendEmail=()=>{
        
    const emailProps= {           
        To: [],
        CC:[],
        Subject: "<Email Subject>",
        Body: "<Email Body>"
    };

    var siteUrl = "www.tahmid.sharepoint.com/sites/RnD"; //Provide your SharePoint site address
    var urlTemplate = siteUrl + "/_api/SP.Utilities.Utility.SendEmail";

    getFormDigest(siteUrl).then((data)=> {
        $.ajax({
            contentType: 'application/json',
            url: urlTemplate,
            type: "POST",
            data: JSON.stringify({
                'properties': {
                    '__metadata': {
                        'type': 'SP.Utilities.EmailProperties'
                    },
                    'To': {
                        'results': emailProps.To
                    },
                    'Body': emailProps.Body,
                    'Subject': emailProps.Subject,
                    'CC': {
                        'results': emailProps.CC
                    },
                }
            }),
            headers: {
                "Accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue
            },
            success: function(data) {
                console.log("Email Sent");
            },
            error: function(err) {
                console.log("Got Error");
            }
        });
    });

}

var getFormDigest=(webUrl)=>{
    return $.ajax({
        url: webUrl + "/_api/contextinfo",
        method: "POST",
        headers: { "Accept": "application/json; odata=verbose" }
    });
}


Here is the way to call the function sendEmail():

$(document).ready(()=>{
    sendEmail();
});

In the real-time use, you can send the emailProps when you call the function as parameter.

So, before ending the article, just a note that if you get a 403 Forbidden error, following two things could be happened in the most cases.

  1. You are not getting the context as in you should check that you are getting the digest.
  2. If that’s not the case, then upgrading to a newer version of jQuery may solve the issue.

Happy Coding. 😊

Leave a Reply

%d bloggers like this: