Rizwan Haider
Rizwan Haider

Reputation: 307

How to send emails using mailgun in angularjs

I am using the following code to send emails in angularjs using the mailgun API.

.controller("MailgunController", function($scope, $http) {

  var mailgunUrl = "YOUR_DOMAIN_HERE";
  var mailgunApiKey = window.btoa("api:key-YOUR_API_KEY_HERE")

  $scope.send = function() {
    $http({
      "method": "POST",
      "url": "https://api.mailgun.net/v3/" + mailgunUrl + "/messages",
      "headers": {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Basic " + mailgunApiKey
      },
      data: "from=" + "[email protected]" + "&to=" + "[email protected]" + "&subject=" + "MailgunTest" + "&text=" + "EmailBody"
    }).then(function(success) {
      console.log("SUCCESS " + JSON.stringify(success));
    }, function(error) {
      console.log("ERROR " + JSON.stringify(error));
    });
  }

})

But I am getting the following error!

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

I had changed the following things in my code

  1. YOUR_DOMAIN_HERE with with-my-domain
  2. key-YOUR_API_KEY_HERE with with-my-api-key

Upvotes: 1

Views: 1797

Answers (1)

Tomislav Stankovic
Tomislav Stankovic

Reputation: 3126

You need to add the following to index.html

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

Also, you can add CORS extension to Google Chrome.

Upvotes: 1

Related Questions