仅使用客户端ajax请求通过mailgun api发送邮件

时间:2017-06-06 14:01:52

标签: ajax email mailgun axios

我正在使用localhost(在静态React网络应用程序内)和表单提交,我想通过我的联系表单发送电子邮件。所以我发布到mailgun api就像这样:

   axios({
      url: 'https://api:key-someapikey@api.mailgun.net/v3/somesandboxdomain1c.mailgun.org/messages',
      method: 'post',
      username: 'api',
      password: 'key-somekey',
      data: {
        from: "Excited User <mailgun@some.example.org>",
        to: "myemail@gmail.com",
        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);
      });

但我不断收到此错误或其中一个错误:

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.

我使用的是静态网络应用,并且没有用于发送数据的服务器。我已经尝试添加和删除各种标题,例如Access-Control-Allow-Headers: Authorization等。似乎无法正常工作

2 个答案:

答案 0 :(得分:2)

不确定我是否回答太晚,但你可以试试这个:

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

Mailgun文档声明它接受请求参数而不是Request Body,因此在您使用的Axios中应使用 params 而不是 data

对于Mailgun所需的Basic Auth,Axios确实提供了一种更好的方法,即提供一个auth对象(参考上面的代码)

您可以参考这些链接了解更多详情

希望这有帮助!

答案 1 :(得分:0)

params适用于{from, to, subject, template},但如果您想使用h:X-My-Variableh:Reply-To之类的v:Recipient-Var,则必须使用data而不是params

axios({
 url: `https://api.mailgun.net/v3/${domain}/messages`,
 method: 'POST',
 auth: {
   username: 'api',
   password: functions.config().mailgun.key, //using firebase functions here
 },
 headers: {
   'Content-Type': 'application/x-www-form-urlencoded'
 },
 data: new URLSearchParams({
   from: `"Foo bot" <noreply@foobot.com>`,
   to: 'foo@bar.com'
   subject: "Hello",
   template: 'my_template',
   'v:customVar': foobar,
 })
})