401 Forbidden when sending email with Swift and Ma

2019-02-26 20:58发布

问题:

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 <(test@test.com)>&to: [my_email_address@gmail.com,(my_email_address@gmail.com)]&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}/messages
response = <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?

回答1:

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)!


回答2:

Finally got it working with the following code, if it helps anyone else:

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 credentials = "api:key-{omitted}"
    request.setValue("Basic \(credentials.toBase64())", forHTTPHeaderField: "Authorization")

    let data = "from: Swift Email <(test@test.com)>&to: [my_email_address@gmail.com,(my_email_address@gmail.com)]&subject:Hello&text:Testing_some_Mailgun_awesomness"
    request.httpBody = data.data(using: String.Encoding.ascii)

    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()
}


extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}

So I guess the answer from William would have worked with:

let base64Credentials = credentials.data(using: String.Encoding.utf8)!.base64EncodedString()

Instead of:

let base64Credentials = credentials.data(using: String.Encoding.utf8)!


标签: swift mailgun