Swift使用MailGun发送电子邮件

时间:2015-10-25 01:18:50

标签: swift api swift2 mailgun

问题

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

迄今为止的研究

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

代码

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!"})

用(个人信息)代替键/信息/电子邮件。

问题

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

谢谢!

4 个答案:

答案 0 :(得分:6)

在python中,auth正在标题中传递。

你必须做一个http post请求,同时传递标题和正文。

这是一个有效的代码:

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

答案 1 :(得分:1)

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

答案 2 :(得分: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问题的人提供解决方案,并希望避免使用第三方解决方案!

答案 3 :(得分: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()
    }
相关问题