Send Email from SharePoint using JSOM

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:
  1. var sendEmail=()=>{  
  2. const emailProps= {  
  3. To: [],  
  4. CC:[],  
  5. Subject: "<Email Subject>",  
  6. Body: "<Email Body>"  
  7. };  
  8. var siteUrl = "www.tahmid.sharepoint.com/sites/RnD"//Provide your SharePoint site address  
  9. var urlTemplate = siteUrl + "/_api/SP.Utilities.Utility.SendEmail";  
  10. getFormDigest(siteUrl).then((data)=> {  
  11. $.ajax({  
  12. contentType: 'application/json',  
  13. url: urlTemplate,  
  14. type: "POST",  
  15. data: JSON.stringify({  
  16. 'properties': {  
  17. '__metadata': {  
  18. 'type''SP.Utilities.EmailProperties'  
  19. },  
  20. 'To': {  
  21. 'results': emailProps.To  
  22. },  
  23. 'Body': emailProps.Body,  
  24. 'Subject': emailProps.Subject,  
  25. 'CC': {  
  26. 'results': emailProps.CC  
  27. },  
  28. }  
  29. }),  
  30. headers: {  
  31. "Accept""application/json;odata=verbose",  
  32. "content-type""application/json;odata=verbose",  
  33. "X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue  
  34. },  
  35. success: function(data) {  
  36. console.log("Email Sent");  
  37. },  
  38. error: function(err) {  
  39. console.log("Got Error");  
  40. }  
  41. });  
  42. });  
  43. }  
  44. var getFormDigest=(webUrl)=>{  
  45. return $.ajax({  
  46. url: webUrl + "/_api/contextinfo",  
  47. method: "POST",  
  48. headers: { "Accept""application/json; odata=verbose" }  
  49. });  
  50. }  
Here is the way to call the function sendEmail(). 
  1. $(document).ready(()=>{  
  2. sendEmail();  
  3. });  
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 most cases.
 
You are not getting the context as in you should check that you are getting the digest.
 
If that’s not the case, then upgrading to a newer version of jQuery may solve the issue.
 
Happy Coding.