Skip to content

Instantly share code, notes, and snippets.

@BasantPandey
Last active June 27, 2021 03:22
Show Gist options
  • Save BasantPandey/05189832546f2c6cc0bd008fcfec3264 to your computer and use it in GitHub Desktop.
Save BasantPandey/05189832546f2c6cc0bd008fcfec3264 to your computer and use it in GitHub Desktop.
Send Email using SharePoint Rest API
var Email= function(){
// Email Either email groupname or email address
var from = 'abc.yahoo.com',
to = 'abc.yahoo.com',
cc = 'abc.yahoo.com',
subject='My Email Subject';
this.options = this.options || {};
this.options['fromEmail'] = this.options['fromEmail'] || {};
this.options['toEmail'] = this.options['toEmail'] || {};
this.options['ccEmail'] = this.options['ccEmail'] || {};
this.options['subject'] = this.options['subject'] || {};
this.options['fromEmail'] = from;
this.options['toEmail'] = to;
this.options['ccEmail'] = cc;
this.options['subject'] = subject;
}
function sendEmail(emailObj,body) {
var that =emailObj;
//Get the relative url of the site
var ServiceUrl = ((_spPageContextInfo.webServerRelativeUrl==='/')?'/':_spPageContextInfo.webServerRelativeUrl);
var siteurl = ServiceUrl;
var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': {
'type': 'SP.Utilities.EmailProperties'
},
'From': that.options.fromEmail,
'To': {
'results': [that.options.toEmail]
},
'CC': {
'results': [that.options.ccEmail]
},
'Body': body,
'Subject': that.options.subject
}
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function (data) {
},
error: function (err) {
// alert('Error in sending Email: ' + JSON.stringify(err));
alert('Error in sending Email', 1);
}
});
}
var sendEmailObj = new Email();
var emailbody = 'hi this is email body';
sendEmail(sendEmailObj,emailbody);
@BasantPandey
Copy link
Author

Update Code with new fixes.

@ahsanranjha
Copy link

are you sure this is working solution with external emails other the own domain?

"{"readyState":4,"responseText":"{"error":{"code":"-2130242040, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The e-mail message cannot be sent. Make sure the e-mail has a valid recipient."}}}","responseJSON":{"error":{"code":"-2130242040, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The e-mail message cannot be sent. Make sure the e-mail has a valid recipient."}}},"status":400,"statusText":"error"}"

@guirkgumbo
Copy link

SharePoint API doesn't allow posts to external emails. Must be an email of a SharePoint user email. This is as much as I know.

@kchaitanyav
Copy link

Can we add multiple email address dynamically for CC?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment