401 Forbidden when sending email with Swift and Mailgun

后端 未结 2 965
慢半拍i
慢半拍i 2021-01-20 03:40

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

func email() {
    let session = URLSession.shared
    let requ         


        
相关标签:
2条回答
  • 2021-01-20 03:53

    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)!
    
    0 讨论(0)
  • 2021-01-20 03:56

    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)!
    
    0 讨论(0)
提交回复
热议问题