Swift使用MailGun发送电子邮件

roc*_*101 2 api mailgun swift swift2

问题

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

迄今为止的研究

据我了解,有两种方法可以通过MailGun 发送电子邮件.一种是通过电子邮件向MailGun发送电子邮件,MailGun将重定向它(请参阅通过SMTP发送).据我所知,这将无法正常工作,因为iOS无法以编程方式自动发送邮件,并且必须使用需要用户干预的方法.因此,我应该直接使用API​​.据我了解,我需要打开一个URL来执行此操作,因此我应该使用某种形式NSURLSession,根据这个SO答案

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!"})
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢!

Wil*_*aan 5

在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()
    }
Run Code Online (Sandbox Code Playgroud)