Ralph David Abernathy Ralph David Abernathy - 1 year ago 137
jQuery Question

How to send an email with Mandrill using JavaScript?

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.

Here is my code:

$('#submitEmail').click(function() {
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',
'type': 'to'
'autotext': 'true',
'subject': 'test',
'html': 'test'
}).done(function(response) {

What am I doing wrong?

Answer Source

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>

You can then access it in your JS file:

var m = new mandrill.Mandrill('your_api_key'); // This will be public

function sendTheMail(){
        "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

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.

I'd also take a look at the full Mandrill docs for send.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download