Search code examples
javascriptajaxmailjet

Couldn't get rid of the multi-origins error when sending an ajax request to mailjet


I'm trying to use the mailjet(as mandrill tests weren't successfuls because sent email remained 'queued' and never reach the box) mailing service in my web application using an AJAX request :

             $.ajax({

                  // The 'type' property sets the HTTP method.
                  // A value of 'PUT' or 'DELETE' will trigger a preflight request.
                  type: 'POST',

                  // The URL to make the request to.
                  url: 'https://api.mailjet.com/v3/send/message',

                  contentType: 'text/plain',

                  data: {
                    'user': '10ca83...public key 1ccd945:f58e84f9d...private key..8e9502fd7a',
                    'from': emaildata.email,
                    'to': 'recipiant@gmail.com',
                    'subject': 'mailjet test',
                    'text': emaildata.msg                   
                  },

                  xhrFields: {                  
                    withCredentials: false
                  },

                  headers: {

                  },

                  success: function() {
                    // Here's where you handle a successful response.
                  },

                  error: function() {
                    // Here's where you handle an error response.
                    // Note that if the error was due to a CORS issue,
                    // this function will still fire, but there won't be any additional
                    // information about the error.
                  }
                }).done(function(response) {
                   console.log(response); // if you're into that sorta thing
                 });
        }

as i got this error in the browsers consoles :

index.php:1 XMLHttpRequest cannot load https://api.mailjet.com/v3/send/message. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401.

I tried to find a solution to get rid of it and i found two solution : 1/ using CORS. 2/ i also found that it can be a problem to send the request from a local web page so i runned a wamp server and i launched the app on it instead directly in browsers.

But i still have that error :/ Any suggestion ? Next i will try the google gmail API for sending email.


Solution

  • Looking at the documentation available in http://dev.mailjet.com - I don't think the API can be used in client-side javascript.

    I think, you need to use a server side technology to talk to the API, that's not unreasonable most other APIs will have the same requirement.

    If you're looking to set up mailjet, they have have written a php wrapper for it https://github.com/mailjet/mailjet-apiv3-php-simple