Sunday 7 August 2016

SharePoint send email jQuery, without server code

You have a requirement or and this is one of the very common scenario to send email from SharePoint using jQuery or client side code...

No problem! we have simple solution, No need to create workflows or server code for emails, just use this simple function:

function UtilitySendEmail(fromEmails, toEmails, emailBody, subject) {

var siteurl = _spPageContextInfo.webServerRelativeUrl;

/* Yes, you can user SPUtility as service that has SendEmail Menthod.*/

var urlTmplt = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
   contentType: 'application/json',
   url: urlTmplt,
   type: "POST",
   data: JSON.stringify({
       'properties': {
           '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
           'From': fromEmails,
           'To': { 'results': [toEmails] },
           'Body': emailBody,
           'Subject': subject
       }
   }
 ),
   headers: {
       "Accept": "application/json;odata=verbose",
       "content-type": "application/json;odata=verbose",
       "X-RequestDigest": $("#__REQUESTDIGEST").val()
   },
   success: function (data) {
      alert("Email has been sent");
   },
   error: function (err) {
       alert(err.responseText);
   }
});
}

You can call this Method to email in SharePoint Online, and SharePoint 2013+ versions.