Swift - Mailgun - 没有收到电子邮件

时间:2017-11-17 06:58:07

标签: ios swift mailgun

我有以下代码使用Mailgun发送电子邮件,我得到响应代码200,据说这意味着电子邮件已成功发送,但我没有收到任何电子邮件,我的Mailgun帐户也没有显示任何内容。

以下是我的代码:

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

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

    let data = "from:Test<(postmaster@BLAHBLAH.mailgun.org)>&to:[BLAH@gmail.com,(BLAH@gmail.com)]&subject:Hello&text:Testing_email"

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

1 个答案:

答案 0 :(得分:0)

我通过对数据变量进行一些调整来实现它,下面是我的工作代码:

func email(){         let request:NSMutableURLRequest = NSMutableURLRequest(url:NSURL(string:“https://api.mailgun.net/v3/sandbox {REPLACE WITH YOURS} .mailgun.org / messages”)!as URL)          request.httpMethod =“POST”

     // Basic Authentication
     let username = "api"
     let password = "key-{REPLACE WITH YOURS}"
     let loginString = NSString(format: "%@:%@", username, password)
     let loginData: NSData = loginString.data(using: String.Encoding.utf8.rawValue)! as NSData
     let base64LoginString = loginData.base64EncodedString(options: [])
     request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

     let bodyStr = "from=Mailgun Sandbox <postmaster@sandbox{REPLACE WITH YOURS}.mailgun.org>&to=Receiver name <SOMEEMAIL@SOMEMEAIL.com>&subject=Test&text=thank you!"

     // appending the data
     request.httpBody = bodyStr.data(using: String.Encoding.utf8);

     let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
     // ... do other stuff here
     })

     task.resume()
}