0
function processSendEmails() {
    
    

    var from = _spPageContextInfo.userLoginName,
        to = _spPageContextInfo.userLoginName,
        body = '<b>Dear xyz ',
        subject = 'Brillio OnTheGO for you!';

    // Call sendEmail function
    //
    sendEmail(from, to, body, subject);
}


function sendEmail(from, to, body, subject) {
    //Get the relative url of the site
    var siteurl = _spPageContextInfo.webAbsoluteUrl;
    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,'onthego@xyz']
                },
                '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('Thanks for choosing OnTheGO , You will receive a mail for OnTheGO app update/ downloads.');
            swal("Thanks for choosing OnTheGO , You will receive a mail for OnTheGO app update/ downloads.");
            
        },
        error: function(err) {
            alert('Error in sending Email: ' + JSON.stringify(err));
        }
    });
}

$(document).ready(function () {

    
$(".sendEmail").click(function(){
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', processSendEmails); 
});

});

I tried this code as mentioned in one of the forums here , but its working for some users and for some its isn't !

3 Answers 3

1

Sample test script, hope it helps.

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script type="text/javascript">
        function SendEmailsToUsers() {
            var ArraySelectedRoles = [{ UserEmail: "user1@xxx.onmicrosoft.com" }, { UserEmail: "user2@xxx.onmicrosoft.com" }];

            var subject = "subject";
            var body = "send email from rest api";
            var from = "sharepointnoreply@gmail.com";
            var restRequests = [];
            for (i = 0; i < ArraySelectedRoles.length; i++) {
                var request = sendEmail(from, ArraySelectedRoles[i].UserEmail, body, subject);
                restRequests.push(request);
            }
            Promise.all(restRequests).then(function () {
                alert("Email send");
            });
        }
        function sendEmail(from, to, body, subject) {
            //Get the relative url of the site
            var siteurl = _spPageContextInfo.webServerRelativeUrl;
            var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
            return $.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()
                }
            });
        }
    </script>
1
  • How can i trigger this event onclick event also to has not been taken as a variable here
    – OM-ॐ
    Jun 18, 2020 at 4:42
1

The REST Endpoint for sending emails will not work in SharePoint Online. if you are specifying the from property. Remove the from property and try again. From property is only supported in SharePoint On-prem.

Here is a working example without the from property. If you try the same example with the from property, it will stop working:

var subject = "SUBJECT OF THE MAIL";
var mailContent = "<h3>Some Heading for the mail</h3><p>Content</p><div>Content</div>";
var toList = ["usser5@contoso.onmicrosoft.com"]

//Send email message over REST
function sendMail(toList, subject, mailContent) {
    var restUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail",
    restHeaders = {
        "Accept": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "Content-Type": "application/json;odata=verbose"
    },
    mailObject = {
        'properties': {
            '__metadata': {
                'type': 'SP.Utilities.EmailProperties'
            },
            'To': {
                'results': toList
            },
            // FROM field is not supported in SharePoint Online
            //'From': 'user@contoso.onmicrosoft.com"',
            'FromDisplay': 'Display From"', // <--- I want a property like this one
            // Important Note: this property does not work in SharePoint Online.
            // the <from> field will always be "no-reply@sharepointonline.com"
            'Subject': subject,
            'Body': mailContent,
            "AdditionalHeaders":
                {
                    "__metadata":
                    { "type": "Collection(SP.KeyValue)" },
                    "results":
                    [
                        {
                            "__metadata": {
                                "type": 'SP.KeyValue'
                            },
                            "Key": "content-type",
                            "Value": 'text/html',
                            "ValueType": "Edm.String"
                        }
                    ]
                }
        }
    };
    return $.ajax({
        contentType: "application/json",
        url: restUrl,
        type: "POST",
        data: JSON.stringify(mailObject),
        headers: restHeaders
    });

} 

$(function(){
 sendMail(toList, subject, mailContent).then(function(data){console.log(data.d)})
}) 

This is a simialr question asked a few years ago.

2
  • My Code was working few months back , it is still working now but only for random people . The issue is this . In your case how can i set an alert here and send it to people from logged in id and one more email id ?
    – OM-ॐ
    Jun 17, 2020 at 5:09
  • I tried my code without from but still alert is coming but mail is not getting triggered . I have an image where i have set a class , that class i am using onclick function to trigger the same in my code
    – OM-ॐ
    Jun 17, 2020 at 5:41
-1

If it is working for some, I would assume it is a permissions issue. RESTful calls are permissions based off of the level of the REST call. Here is a copy of a post I made on this subject a while back

REST API calls are still based on permissions as to what you will be able to use when it is invoked. This sounds like a permissions issue. You are SCA sure but you do not own the WFE. So this is why the Farm Admins can see everything and SCA cannot.

We can map user permissions with role definitions

Full Control - Has full control - User can make any call under endpoint "_api/web"

Edit - Can add, edit and delete lists; can view, add, update and delete list items and documents. - User Can do any operation on list and list items and end point would be "_api/web/Lists"

Read - Can view pages and list items and download documents. - User can do Get operations on list items and end point would be "_api/web/Lists/getByTitle('')/Items

Since your call is just using the _api endpoint, the permissions go up just like the others. You will not be able to see anything as SCA unless it is using the _api/web end point. At least not everything.

1
  • Everyone is having read access accept me as i am a site collection admin ! Its like random people who are able to do so ...
    – OM-ॐ
    Jun 17, 2020 at 4:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.