401 Forbidden when sending email with Swift and Mailgun
<p>I have the following code but consistently get error 401 forbidden when attempting to run it:</p>

<pre><code>func email() {
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/{edited_out}/messages")! as URL)
    request.httpMethod = "POST"
    let data = "from: Swift Email &lt;(test@test.com)&gt;&amp;to: [my_email_address@gmail.com,(my_email_address@gmail.com)]&amp;subject:Hello&amp;text:Testing_some_Mailgun_awesomness"
    request.httpBody = data.data(using: String.Encoding.ascii)
    request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.setValue("key-{edited_out}", forHTTPHeaderField: "api")
    let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}
</code></pre>

<p>The error is:</p>

<pre><code>    url = https://api.mailgun.net/v3/{edited_out}/messages
response = &lt;NSHTTPURLResponse: 0x600000226a20&gt; { URL: https://api.mailgun.net/v3/{edited_out}/messages } { status code: 401, headers {
    Connection = "keep-alive";
    "Content-Length" = 9;
    "Content-Type" = "text/html; charset=utf-8";
    Date = "Thu, 29 Dec 2016 21:22:46 GMT";
    Server = nginx;
    "Www-Authenticate" = "Basic realm=\"MG API\"";
} }
response code = 401
</code></pre>

<p>If I send such a request via curl with my credentials it works fine.</p>

<p>Any ideas?</p>