问题
I am struggling with this desperately. I want to collect an array of email addresses from a checkboxed table (some checked but not all) and pass them to Mandrill JavaScript code to send.
There are 2 issues here:
- How to send multiple emails in general and
- How to pass an array to the mandrill code to execute email sending.
The code is:
<script>
function log(obj) {
$('#response').text(JSON.stringify(obj));
}
function sendTheMail() {
// Send the email!
alert('scripting');
var emails = [];
var first = [];
var last = [];
$('tr > td:first-child > input:checked').each(function() {
//collect email from checked checkboxes
emails.push($(this).val());
first.push($(this).parent().next().next().text());
last.push($(this).parent().next().next().next().text());
});
var new_emails = JSON.stringify(emails);
alert(new_emails);
//create a new instance of the Mandrill class with your API key
var m = new mandrill.Mandrill('my_key');
// create a variable for the API call parameters
var params = {
"message": {
"from_email": "rich@pachme.com",
"to": [{"email": new_emails}],
"subject": "Sending a text email from the Mandrill API",
"text": "I'm learning the Mandrill API at Codecademy."
}
};
m.messages.send(params, function(res) {
log(res);
},
function(err) {
log(err);
});
}
</script>
The alert of the array of email addresses is:
["richardwi@gmail.com","richard.illingworth@refined-group.com","mozartfm@gmail.com"]
and the resulting error message is:
[{"email":"[\"richardwi@gmail.com\",\"richard.illingworth@refined-group.com\",\"mozartfm@gmail.com\"]","status":"invalid","_id":"0c063e8703d0408fb48c26c77bb08a87","reject_reason":null}]
On a more general note, the following works for just one email address:
"to": [{"email" : "user@gmail.com"}],
but
"to": [{"email" : "user@gmail.com", "anotheruser@gmail.com"}],
does not, so I am not even able to hard code a multiple send.
Any ideas? All help gratefully received.
回答1:
This is invalid javascript "to": [{"email": "email1", "email2"}]
Change it to
"to": [{"email": "email1"},{"email": "email2"}]
In javascript the []
is an array and {}
is an object with key/value pairs. So "to" should be an array of objects like {"email": "some@email.com"}
Edit
To map your array of emails to an array of such objects you can for instance use jQuery.map
// Try doing something like this
var emailObjects = $.map(emails, function(email) {
return {"email": email};
});
And then change your params
to the following
var params = {
"message": {
"from_email": "rich@pachme.com",
"to": emailObjects,
"subject": "Sending a text email from the Mandrill API",
"text": "I'm learning the Mandrill API at Codecademy."
}
};
来源:https://stackoverflow.com/questions/16870859/jquery-sending-email-with-mandrill-from-an-array