我拼命地挣扎着。我想从一个已复选的表中收集一组电子邮件地址(一些已检查但不是全部)并将它们传递给Mandrill JavaScript代码以进行发送。
这里有两个问题:
代码是:
<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>
电子邮件地址数组的提醒是:
["richardwi@gmail.com","richard.illingworth@refined-group.com","mozartfm@gmail.com"]
,生成的错误消息为:
[{"email":"[\"richardwi@gmail.com\",\"richard.illingworth@refined-group.com\",\"mozartfm@gmail.com\"]","status":"invalid","_id":"0c063e8703d0408fb48c26c77bb08a87","reject_reason":null}]
更一般地说,以下仅适用于一个电子邮件地址:
“to”:[{“email”:“user@gmail.com”}],
但是
“to”:[{“email”:“user@gmail.com”,“anotheruser@gmail.com”}],
没有,所以我甚至无法硬编码多次发送。
有什么想法吗?感谢所有的帮助。
答案 0 :(得分:1)
这是无效的javascript "to": [{"email": "email1", "email2"}]
将其更改为
"to": [{"email": "email1"},{"email": "email2"}]
在javascript中,[]
是一个数组,{}
是一个具有键/值对的对象。所以&#34;到&#34;应该是像{"email": "some@email.com"}
修改强>
要将您的电子邮件数组映射到此类对象的数组,您可以使用jQuery.map
// Try doing something like this
var emailObjects = $.map(emails, function(email) {
return {"email": email};
});
然后将params
更改为以下
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."
}
};