Swift – 401 Forbidden when sending email with Swift and Mailgun

mailgun, swift

I have the following code but consistently get error 401 forbidden when attempting to run it:

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 <([email protected])>&to: [[email protected],([email protected])]&subject:Hello&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()}

The error is:

    url = https://api.mailgun.net/v3/{edited_out}/messagesresponse = <NSHTTPURLResponse: 0x600000226a20> { 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

If I send such a request via curl with my credentials it works fine.

Any ideas?

Best Solution

You need to set the uesrname and the password.

Something like this:

request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

and base64Credentials is the :

let credentials= String(format: "%@:%@", username, password)let base64Credentials= credentials.data(using: String.Encoding.utf8)!