Problem
我想使用MailGun从纯 Swift 应用程序发送电子邮件的服务。
迄今为止的研究
据我了解,有两种发送电子邮件的方法通过邮件枪。一种是向 MailGun 发送电子邮件,MailGun 将重定向它(请参阅通过 SMTP 发送)。据我了解,这不起作用,因为 iOS 无法以编程方式自动发送邮件,并且必须使用需要用户干预的方法。因此,我应该直接使用 API。据我了解,我需要打开一个 URL 来执行此操作,因此我应该使用某种形式NSURLSession
, 按照这个答案
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": ["[email protected]", "(Personal info)"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
用(个人信息)代替密钥/信息/电子邮件。
Question
我如何在 Swift 中做到这一点?
Thanks!
在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: [[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()
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)