首页 文章

Swift使用MailGun发送电子邮件

提问于
浏览
2

Problem

我想使用MailGun服务从纯粹的Swift应用程序发送电子邮件 .

Research So Far

据我了解,there are two methods to send an email通过MailGun . 一种是通过电子邮件向MailGun发送电子邮件,MailGun将重定向它(请参阅通过SMTP发送) . 据我所知,这将无法正常工作,因为iOS无法以编程方式自动发送邮件,并且必须使用methods that require user intervention . 因此,我应该直接使用API . 据我了解,我需要打开一个URL来执行此操作,因此我应该使用某种形式的 NSURLSession ,根据this SO answer

Code

MailGun提供了Python的文档,如下所示:

def send_simple_message():
return requests.post(
    "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages",
    auth=("api", "key-(Personal info)"),
    data={"from": "Excited User <(Personal info)>",
          "to": ["bar@example.com", "(Personal info)"],
          "subject": "Hello",
          "text": "Testing some Mailgun awesomness!"})

用(个人信息)代替密钥/信息/电子邮件 .

Question

我如何在Swift中做到这一点?

谢谢!

4 回答

  • 1

    在python中, auth 正在 Headers 中传递 .

    你必须做一个http post请求,传递 Headers 和正文 .

    这是一个有效的代码:

    func test() {
            let session = NSURLSession.sharedSession()
            let request = NSMutableURLRequest(URL: NSURL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
            request.HTTPMethod = "POST"
            let data = "from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
            request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
            request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
            let task = session.dataTaskWithRequest(request, 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! NSHTTPURLResponse
                    print("response code = \(httpResponse.statusCode)")
                }
    
    
            })
            task.resume()
        }
    
  • 5

    requests.post发送HTTP POST请求,将键/值对编码为 application/x-www-form-urlencoded . 你需要做同样的事情 .

  • 1

    我花了好几个小时试图让选定的答案工作,但无济于事 .

    虽然我终于能够通过大型HTTP响应使其正常工作 . 我把完整的路径放到Keys.plist中,这样我就可以将我的代码上传到github,并将一些参数分解为变量,这样我就可以在以后的程序中设置它们 .

    // Email the FBO with desired information
    // Parse our Keys.plist so we can use our path
    var keys: NSDictionary?
    
    if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
        keys = NSDictionary(contentsOfFile: path)
    }
    
    if let dict = keys {
        // variablize our https path with API key, recipient and message text
        let mailgunAPIPath = dict["mailgunAPIPath"] as? String
        let emailRecipient = "bar@foo.com"
        let emailMessage = "Testing%20email%20sender%20variables"
    
        // Create a session and fill it with our request
        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)
    
        // POST and report back with any errors and response codes
        request.HTTPMethod = "POST"
        let task = session.dataTaskWithRequest(request, 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! NSHTTPURLResponse
                print("response code = \(httpResponse.statusCode)")
            }
        })
        task.resume()
    }
    

    Mailgun Path在Keys.plist中作为名为mailgunAPIPath的字符串,其值为:

    https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?
    

    希望这为其他任何遇到MailGun问题并希望避免第三方解决方案的人提供解决方案!

  • 1

    斯威夫特3回答:

    func test() {
            let session = URLSession.shared
            var request = URLRequest(url: URL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
            request.httpMethod = "POST"
            let data = "from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
            request.httpBody = data.data(using: .ascii)
            request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
            let task = session.dataTask(with: request, 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()
        }
    

相关问题