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 回答
在python中,
auth
正在 Headers 中传递 .你必须做一个http post请求,传递 Headers 和正文 .
这是一个有效的代码:
requests.post发送HTTP POST请求,将键/值对编码为
application/x-www-form-urlencoded
. 你需要做同样的事情 .根据How to escape the HTTP params in Swift将键值对集转换为
application/x-www-form-urlencoded
使用结果字符串为数据撰写请求并按iOS : http Post using swift发送
我花了好几个小时试图让选定的答案工作,但无济于事 .
虽然我终于能够通过大型HTTP响应使其正常工作 . 我把完整的路径放到Keys.plist中,这样我就可以将我的代码上传到github,并将一些参数分解为变量,这样我就可以在以后的程序中设置它们 .
Mailgun Path在Keys.plist中作为名为mailgunAPIPath的字符串,其值为:
希望这为其他任何遇到MailGun问题并希望避免第三方解决方案的人提供解决方案!
斯威夫特3回答: