gpt4 book ai didi

swift - 使用 Swift 和 Mailgun 发送电子邮件时出现 401 Forbidden

转载 作者:搜寻专家 更新时间:2023-11-01 05:35:33 24 4
gpt4 key购买 nike

我有以下代码,但在尝试运行它时始终收到错误 401 forbidden:

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

错误是:

    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

如果我使用我的凭据通过 curl 发送此类请求,它会正常工作。

有什么想法吗?

最佳答案

您需要设置用户名和密码。

是这样的:

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

base64Credentials是:

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

关于swift - 使用 Swift 和 Mailgun 发送电子邮件时出现 401 Forbidden,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41387402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com