使用MailGun快速发送电子邮件

使用MailGun快速发送电子邮件

本文介绍了使用MailGun快速发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

问题

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

I would like to use the MailGun service to send emails from a pure Swift app.

到目前为止的研究

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

As I understand it, there are two methods to send an email via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See Send via SMTP). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use methods that require user intervention. As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of NSURLSession, as per this SO answer

代码

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

MailGun provides documentation for Python, which is as follows:

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": ["[email protected]", "(Personal info)"],
          "subject": "Hello",
          "text": "Testing some Mailgun awesomness!"})

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

with (Personal info) being substituted for keys/information/emails.

问题

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

How do I do that in Swift?

谢谢!

推荐答案

在python中,auth在标头中传递.

In python, the auth is being passed in the header.

您必须执行http发布请求,同时传递标头和正文.

You have to do a http post request, passing both the header and the body.

这是一个有效的代码:

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: [[email protected],(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()
    }

这篇关于使用MailGun快速发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:10