Swift:Mailgun 401 响应代码--未提供有效的 API 密钥

Swift: Mailgun 401 response code--No valid API key provided

所以我有如下所示的发送电子邮件功能:

func email() {
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/sandbox################################/messages")! as URL)

    request.httpMethod = "POST"
    let credentials = "api:key-################################-########-########"
    request.setValue("Basic \(credentials.toBase64())", forHTTPHeaderField: "Authorization")

    let data = "from: Swift Email <(test@test.com)>&to: [myemail@gmail.com,(myemail@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()
}

所以我猜要么是我的 API 键错了,要么我的请求 URL 错了。为了找到我的请求 URL,我转到 https://app.mailgun.com/app/dashboard and then scrolled down to the Sending Domains section and copied that. To get my API key I went to https://app.mailgun.com/app/account/security/api_keys 并复制了私钥 API。我真的不确定为什么我会收到这个无效代码——如果你弄明白了,提前谢谢你!

旁注:不太确定数据常量是否设置正确(就缺少或有太多括号而言),所以如果你也能检查一下那就太好了。

我有一个名为“paw”的软件,它有助于形成 REST API 调用 Xcode、curl、php 等

不知道对你有没有帮助

class MyRequestController {
    func sendRequest(somevar: String, completion: @escaping (Books) -> Void) {
        /* Configure session, choose between:
           * defaultSessionConfiguration
           * ephemeralSessionConfiguration
           * backgroundSessionConfigurationWithIdentifier:
         And set session-wide properties, such as: HTTPAdditionalHeaders,
         HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
         */
        let sessionConfig = URLSessionConfiguration.default

        /* Create session, and optionally set a URLSessionDelegate. */
        let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

        /* Create the Request:
            (POST https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages)
         */

        guard var URL = URL(string: "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages") else {return}
        var request = URLRequest(url: URL)
        request.httpMethod = "POST"

        // Headers

        request.addValue("Basic YXBpOllPVVJfQVBJX0tFWQ==", forHTTPHeaderField: "Authorization")
        request.addValue("multipart/form-data; charset=utf-8; boundary=__X_PAW_BOUNDARY__", forHTTPHeaderField: "Content-Type")

        // Body

        let bodyString = "--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"from\"\r\n\r\n'Excited User <mailgun@YOUR_DOMAIN_NAME>'\r\n--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"to\"\r\n\r\nYOU@YOUR_DOMAIN_NAME\r\n--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"to\"\r\n\r\nbar@example.com\r\n--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"subject\"\r\n\r\n'Hello'\r\n--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\n'Testing some Mailgun awesomeness!'\r\n--__X_PAW_BOUNDARY__--\r\n"
        request.httpBody = bodyString.data(using: .utf8, allowLossyConversion: true)

        /* Start a new Task */
        let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
            if (error == nil) {
                // Success
                let statusCode = (response as! HTTPURLResponse).statusCode
                print("URL Session Task Succeeded: HTTP \(statusCode)")
            }
            else {
                // Failure
                print("URL Session Task Failed: %@", error!.localizedDescription);
            }
        })
        task.resume()
        session.finishTasksAndInvalidate()
    }
}

**** 并且你可以像这样调用这个函数

MyRequestController().sendRequest(somevar: "something")

查看 https://www.youtube.com/watch?v=44APgBnapag 了解更多详情 本教程展示如何使用 Xcode 进行 REST API 调用,此示例扫描条形码,通过调用 API 和 return 信息的函数发送扫描的代码。 ..