4

I can do this:

curl --user 'api:MYAPIKEY' -F from=foo@bar.it -F to=MYEMAIL@gmail.com -F subject='foo' -F text='bar' https://api.mailgun.net/v3/sandbox93d8299f673a4c3295b7592956cb3d9.mailgun.org/messages

but I get a login popup when I try to do the same request with jquery .ajax() method:

$.ajax({
    headers: {"Authorization": "Basic api:key-b50a9065a7b9bdf464f3d7a418ca96bb"},
    // url: "././mail/contact_me.php",
    url: "https://api.mailgun.net/v3/sandbox93d8299f673a4c32952b7592956cb3d9.mailgun.org/messages",
    type: "POST",
    dataType: 'json',
    data: {
        name: name,
        phone: phone,
        email: email,
        message: message
    },
    // cache: false,
    success: function() {
        alert('ok');
    },
    error: function() {
        alert('problems');
    }
}

enter image description here

The server respond with a 401. any idea why?

thank you

masciugo
  • 1,113
  • 11
  • 19
  • There’s a detailed answer for this at https://stackoverflow.com/questions/50076659/mailgun-api-request-header-field-authorization-is-not-allowed-by-access-control/50081948#50081948 – sideshowbarker Apr 28 '18 at 23:41

1 Answers1

5

Try using the username and password fields

$.ajax({
    url: "https://api.mailgun.net/v3/sandbox93d8299f673a4c32952b7592956cb3d9.mailgun.org/messages",
    type: "POST",
    dataType: 'json',
    username:'api',
    password: 'key-b50a9065a7b9bdf464f3d7a418ca96bb',
    ...

If you're setting the header yourself you have to base64 encode it

headers: {"Authorization": "Basic "+btoa("api:key-b50a9065a7b9bdf464f3d7a418ca96bb")},
Musa
  • 96,336
  • 17
  • 118
  • 137
  • 1
    Great! I wonder why [official docs](https://documentation.mailgun.com/quickstart-sending.html) have examples for many langs but not for Javascript.. Thanks a lot – masciugo May 18 '15 at 19:22
  • 3
    @masciugo how did you overcome the `Access-Control-Allow-Origin` or `Access-Control-Allow-Headers` limitations? – cYrus Aug 03 '15 at 18:20
  • 1
    @cYrus Were you able to solve the Access-Control-Allow-Origin or Access-Control-Allow-Headers limitation ? – Miguelme Jun 02 '16 at 00:19
  • @user3457759 Now I can't remember all the details but I ended up using this in a Chrome extension with no problems; I assume checks are not so strict there. MailGun clearly doesn't want to support JavaScript as that would require to publicly expose the secret API key. – cYrus Jun 02 '16 at 20:07
  • @cYrus Yes I think they just don't allow you to use JS. Forcing you to create at least a little backend to handle this. – Miguelme Jun 04 '16 at 15:20