Search code examples
ajaxmiddlemanmailgun

Cannot pass authentication sending ajax request to mailgun


I can do this:

curl --user 'api:MYAPIKEY' -F [email protected] -F [email protected] -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


Solution

  • 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")},