Domanda

I have function like this:

function sendEmail() {

var appweburl = _spPageContextInfo.webAbsoluteUrl;
var urlTemplate = appweburl + "/_api/SP.Utilities.Utility.SendEmail";


var fieldName = "Notificar a";
var body = "Descripción";
var _body = $("textarea[title^='" + body + "']");

var fullURL = window.location.href
var url = new URL(fullURL ); 
var ID = url.searchParams.get("ID");


var _PeoplePicker = $("div[title='" + fieldName + "']");
var emailSpan = $(_PeoplePicker).find('.sp-peoplepicker-userSpan');
var _sid ="";
var arrEmailID = [];

if (emailSpan.length > 0) {


$(emailSpan).each((index,el) => {
 arrEmailID.push(`'${$(el).attr('sid').split("|")[2]}'`);
});

} else {
       alert("null");
}

        var fieldUsuario = _sid;
        var fromMail = 'emaik@domain.com';
        var subject = 'Tarea Editada: ' + 'ID: ' +ID + ' ' + _body.val();
        var body = 'Se ha editado la tarea: '+ 'ID: ' + ID+ ' ' + 'Descripción: ' + _body.val() ;    

    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: "POST",
        data: JSON.stringify({
            'properties': {
                '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                'From': fromMail,
                'To': { 'results': [arrEmailID] },
                'Body': body, 
                'Subject': subject
            }
        }
      ),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            var result = data.d.results;

        },
        error: function (err) {
            alert(JSON.stringify(err));
        }
    });
}

As you can see I have var arrEmailID = []; it populates foreach emailSpan I receive, so at the final of the day I have something like this: enter image description here

I want to know if its possible to execute ajax call foreach item arrEmailID and use that item in To': { 'results': [arrEmailID] },

È stato utile?

Soluzione

I've only done this in SP 2013 on-prem. So there may be slight differences. First thing I notice is that in your array of recipients you've got both double and single quotes. So that probably isn't quite right. I have used SP.Utilities.Utility.SendEmail to send:

["i:0#.w|<domain>\<userId>", "i:0#.w|<domain>\<userId>"]

I know that will need to be different for SP Online, but I don't know exactly how. But it should only have one set of quotation marks around each element.

But here is the part for making multiple rest calls. Looking at your code I think you are using jQuery to handle the ajax portion of your call, so that is what my code is using too. I'm also going to get rid of the success and fail callbacks and make use of the deffered/promises included in $.ajax. You will need to rearrange your code a bit. Basically take the part that sets up and gets all your variables into one function and then passes them to the send function.

  var appweburl = _spPageContextInfo.webAbsoluteUrl;
  var urlTemplate = appweburl + "/_api/SP.Utilities.Utility.SendEmail";
  var headers = {
      "Accept": "application/json;odata=verbose",
      "content-type": "application/json;odata=verbose",
      "X-RequestDigest": $("#__REQUESTDIGEST").val()
  };

  function prepareEmails() {

      // code to get users info configure the body and subect

      // this pattern allows for multiple REST calls
      var promises =[];

      arrEmailID.forEach(function(recipient){

          promises.push(sendEmail(recipient,fromMail,body,subject));

      });

      // this will resolve when all of the promises are resolved
      return $.when.apply(null,promises);
  }


  function sendEmail(recipient, fromMail, body, subject) {

      // if recipient isn't an array make it one
      recipient = Array.isArray(tmp) ? recipient : [recipient];

      var payload = {'properties': {
                        '__metadata': { 'type': 'SP.Utilities.EmailProperties'},
                        'From': fromMail,
                        'To': {'results': recipient},
                        'Body': body,
                        'Subject': subject
                      }
      };

      return $.ajax({
          contentType: 'application/json',
          url: urlTemplate,
          type: "POST",
          headers: headers,
          data: JSON.stringify(payload)
      });
  }

  ...

  // kick it all off later with

  function sendNotices(e){
    prepareEmails()
      .done(function(){

        // if there were multiple rest calls there will be multiple results
        // if there was only one there won't be

        var results = Array.prototype.slice.call(arguments);

        if(!Array.isArray(results[0])){
          results = [results];  
        }

        // do whatever you need to do with the results from each call

      })
      .fail(function(err){
        alert(JSON.stringify(err));
      });
  }

button.addEventListener('click',sendNotices);

Altri suggerimenti

It should work by adding a ; between each emails:

'To': { 'results': arrEmailID.join("; ") },

For example : abc@abc.com; test@abc.com; ta@abc.com; tessss@abc.com

If it doesn't work, then you can send emails one by one using PromiseChain function below:

function PromiseChain(arr, fct) {
  var dfd = jQuery.Deferred().resolve();
  var res = arr.map(function(item,idx) {
    dfd = dfd.then(function() {
      return fct(item,idx)
    });
    return dfd
  });
  return jQuery.when.apply(null, res)
}

function sendEmail() {
  var appweburl = _spPageContextInfo.webAbsoluteUrl;
  var urlTemplate = appweburl + "/_api/SP.Utilities.Utility.SendEmail";

  var fieldName = "Notificar a";
  var body = "Descripción";
  var _body = $("textarea[title^='" + body + "']");

  var fullURL = window.location.href
  var url = new URL(fullURL );
  var ID = url.searchParams.get("ID");

  var _PeoplePicker = $("div[title='" + fieldName + "']");
  var emailSpan = $(_PeoplePicker).find('.sp-peoplepicker-userSpan');
  var _sid ="";
  var arrEmailID = [];

  if (emailSpan.length > 0) {
    $(emailSpan).each((index,el) => {
     arrEmailID.push(`'${$(el).attr('sid').split("|")[2]}'`);
    });
  } else {
    alert("null");
  }

  var fieldUsuario = _sid;
  var fromMail = 'emaik@domain.com';
  var subject = 'Tarea Editada: ' + 'ID: ' +ID + ' ' + _body.val();
  var body = 'Se ha editado la tarea: '+ 'ID: ' + ID+ ' ' + 'Descripción: ' + _body.val() ;

  // use PromiseChain here with "arrEmailID"
  PromiseChain(arrEmailID, function(email) {
    var deferred = jQuery.Deferred();
    $.ajax({
      contentType: 'application/json',
      url: urlTemplate,
      type: "POST",
      data: JSON.stringify({
        'properties': {
          '__metadata': {
            'type': 'SP.Utilities.EmailProperties'
          },
          'From': fromMail,
          'To': {
            'results': email
          },
          'Body': body,
          'Subject': subject
        }
      }),
      headers: {
        "Accept": "application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
      },
      success: function(data) {
        var result = data.d.results;
        console.log("Email sent to "+email)
        deferred.resolve()
      },
      error: function(err) {
        alert(JSON.stringify(err));
        deferred.reject()
      }
    });
    $.ajax({
      url:'http://api.jQuery.com/'+item,
      success:function(data, textStatus) {
        console.log(textStatus);
        deferred.resolve()
      },
      error:function() {
        deferred.reject()
      }
    })
    return deferred;
  }).done(function() {
    var nbEmails = arguments.length;
    alert(nbEmails + " email"+(nbEmails>1?"s":"")+" sent !")
  })
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top