如何使用JavaScript发送带有Mandrill的电子邮件?

问题描述:

我已经遵循指南使用Mandrill使用JavaScript发送电子邮件,但是在我的控制台中收到此错误:跨原始请求已被阻止:同源策略不允许在https://mandrillapp.com/api/上读取远程资源1.0 /消息/ send.json。这可以通过将资源移动到相同的域或启用CORS来修复。

I have followed this guide on how to send an email using JavaScript with Mandrill, but am receiving this error in my console: 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);
  });
});

我做错了什么?

而不是发出POST请求,您应该包括< head> $ c中< script> 标签中的js =nofollow> Mandrill API $ c>:

Rather than making a POST request, you should include the Mandrill API in a <script> tag in your <head>:

<script type="text/javascript" src="path_to_locally_stored_copy_of_mandrill_API"></script>

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

You can then access it in your JS file:

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 ,因为它将使用开发工具从客户端访问。这可以打开你的网络钓鱼漏洞,有人可能会滥用你的密钥。

However, note that this will expose your API to the public, as it will be accessible from the client side using dev tools. This can open you up to phishing vulnerabilities and someone could abuse your key.

我还会看看完整的Mandrill文档 发送