sp.utilities.utility.sendemail + how to send email to multiple users
-
21-01-2021 - |
Question
Below is my code to send email through SharePoint (2016 OnPrem)
function sendEmail(from, to,subject,body) {
//Get the relative url of the site
var siteurl = _spPageContextInfo.webServerRelativeUrl;
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': from,
'To': {
'results': [to]
},
'Body': body,
'Subject': subject
}
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function(data) {
//alert('Email Sent Successfully');
var isSent = true;
},
error: function(err) {
alert('Error in sending Email to System Admin: ' + JSON.stringify(err));
}
});
}
and below is my calling statement;
sendEmail("abc@def.com","a@b.com,b@b.com","Test Subject","Test Body");
Email gets sent when there is 1 user. However when trying with multiple users getting error
Error in sending Email to System Admin: {"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":"Bad Request"}
Kindly let know how to put multiple users in TO. Tried with ; seperated email addresses. However same error.
Thank you
Solution
The format of your "To" variable must be an Array witch contains emails (or domain\login). Here, you pass a string witch contains email separated by comma.
Try somthing like :
var recipients = ["a@b.com","b@b.com"];
sendEmail("abc@def.com",recipients ,"Test Subject","Test Body");
And change the "data" in your query like :
data: JSON.stringify({
'properties': {
'__metadata': {
'type': 'SP.Utilities.EmailProperties'
},
'From': from,
'To': {
'results': to
},
'Body': body,
'Subject': subject
}
})
Like kasper said, your recipent must be a SharePoint site users. (And the From too) You can't send Email from sharepoint to other email who are not in your organisation
check this link for an exemple : SharePoint 2013: REST API/Client Code to send mails