如何使用JavaScript向Mandrill发送电子邮件?

我已经按照本指南关于如何使用Mandrill使用JavaScript发送电子邮件,但是在我的控制台中收到此错误: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mandrillapp.com/api/1.0/messages/send.json. This can be fixed by moving the resource to the same domain or enabling CORS. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mandrillapp.com/api/1.0/messages/send.json. This can be fixed by moving the resource to the same domain or enabling CORS.

这是我的代码:

 $('#submitEmail').click(function() { $.ajax({ type: "POST", url: "https://mandrillapp.com/api/1.0/messages/send.json", data: { 'key': 'my_api_key', 'message': { 'from_email': 'test@hotmail.com', 'to': [{ 'email': 'test@gmail.com', 'name': 'RECIPIENT NAME (OPTIONAL)', 'type': 'to' }], 'autotext': 'true', 'subject': 'test', 'html': 'test' } } }).done(function(response) { console.log(response); }); }); 

我究竟做错了什么?

您应该在标记中包含Mandrill API ,而不是发出POST请求:

  

然后,您可以在JS文件中访问它:

 var m = new mandrill.Mandrill('your_api_key'); // This will be public function sendTheMail(){ m.messages.send({ "message": { "from_email": "your_email_address", "from_name": "your_name", "to":[{"email": "someone's_email_address", "name": "someone's_name"}], // Array of recipients "subject": "optional_subject_line", "text": "Text to be sent in the body" // Alternatively, use the "html" key to send HTML emails rather than plaintext } }); } 

请注意,这会将您的API暴露给公众 ,因为可以使用开发工具从客户端访问它。 这可以打开您的网络钓鱼漏洞,有人可能会滥用您的密钥。

我还要看一下完整的Mandrill docs for send

很酷,这是使用Jquery发送表单的解决方案。 🙂

我试图使用jquery + mandrill在我的网站上建立联系表格。 我没有发现上面的答案有帮助(没有进攻兄弟)所以我希望我的答案可以解决这个问题。 我得到了我的好朋友和开发人员Thomas Lane @ d00by的帮助。

请参阅下面的表格。 在我的forms下面的javascript。

  • 创建表单
  • 使用ajax提交表单
  • 返回false
  • 提交时调用函数。

要使用mandrill,您需要一个API密钥。

 
function submitContactForm() { /*var name = $('#form_name').val(); var email = $('#form_email').val(); var phone = $('#form_phone').val(); var message =$('#form_message').val();*/ //this is the html template. You can also do it as used above. But is much simpler done as below var htmlMessage = 'Contact form
' + 'Name: '+$('#form_name').val()+'
'+ 'EMail: '+$('#form_email').val()+'
'+ 'Message
'+ $('#form_message').val(); //submit the form using ajax $.ajax({ type: "POST", url: "https://mandrillapp.com/api/1.0/messages/send.json", data: { "key": 'Your API key here', "message": { "from_email": 'your email', "to": [ { "email": 'form email', "name": 'name', "type": 'to' } ], "subject": 'Subject', "html": htmlMessage } } }); return false; }

您无法从浏览器访问Mandrill API – 出于安全原因,这是设计使然。 了解您的API密钥将如何向访问您网站的任何人公开?

您需要向服务器发出AJAX请求,然后从后端应用程序代码中调用Mandrill API。