Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending mail through mailgun api using only client side ajax request

I am working on localhost (inside a static React web app) and on form submit, I want to send an email through my contact form. So I am posting to the mailgun api like so:

   axios({
      url: 'https://api:[email protected]/v3/somesandboxdomain1c.mailgun.org/messages',
      method: 'post',
      username: 'api',
      password: 'key-somekey',
      data: {
        from: "Excited User <[email protected]>",
        to: "[email protected]",
        subject: "Hello from react app",
        text: "Testing some Mailgun awesomness!"
      },
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        'Authorization': `Basic ${window.btoa('api:key-someapikey')}`
      }
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

But I keep getting this error or one of it's variations:

XMLHttpRequest cannot load https://api.mailgun.net/v3/somesandbox.mailgun.org. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

I am using a static web app and have no server through which to send data. I have already tried adding and removing various headers such as Access-Control-Allow-Headers: Authorization etc. Nothing seems to work

like image 758
Amit Erandole Avatar asked Dec 01 '25 11:12

Amit Erandole


1 Answers

Not sure if I'm answering it too late, but you can try this:

axios({
    method: 'post',
    url: `${mailgun.baseUrl}/${mailgun.domain}/messages`,
    auth: {
        username: 'api',
        password: mailgun.apiKey
    },
    params: {
        from: 'Awesome Development Team <[email protected]>',
        to: '[email protected]',
        subject: 'Hello',
        text: 'Welcome to the team!'
    }
}).then(
    response => {
        console.log(response)
    },
    reject => {
        console.log(reject)
    }
)

Mailgun documentation states that it accepts Request Parameters instead of Request Body, so in Axios you use should use params instead of data.

As for the Basic Auth required by Mailgun, Axios does provide a better way to do so, that is supplying a auth object (Refer to the code above)

You can refer to these links for more details

  • https://documentation.mailgun.com/en/latest/api-sending.html#sending
  • https://github.com/axios/axios (Scroll to Request Config)

Hope this helps!

like image 94
howard Avatar answered Dec 07 '25 14:12

howard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!