401 Forbidden when sending email with Swift and Mailgun

拈花ヽ惹草 提交于 2019-12-02 01:07:34

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

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)!
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!