swift2 使用MailGun快速发送电子邮件

mdfafbf1  于 2022-11-06  发布在  Swift
关注(0)|答案(5)|浏览(206)

问题

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

目前为止的研究

据我所知,通过MailGun发送邮件有两种方法,一种是将邮件发送到MailGun,MailGun会将邮件重定向(请参阅 * 通过SMTP发送 *)。据我所知,这是行不通的,因为iOS无法通过编程自动发送邮件,必须使用methods that require user intervention。因此,我应该直接使用API。据我所知,我需要打开一个URL来完成此操作,所以我应该使用某种形式的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中做到这一点?
谢谢你!

zsohkypk

zsohkypk1#

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

yks3o0rb2#

人们会收到400或401错误,因为其他答案都无法正确构建URL。以下是一些可在swift 5和iOS15中运行的代码:

func sendEmail() {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = "https://api:YOUR_API_KEY@api.mailgun.net/v3/YOUR_DOMAIN/messages?"
    let emailRecipient = "RECIPIENT@EMAIL.COM"
    let emailMessage = "Testing%20email%20sender%20variables"
    // Create a session and fill it with our request
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + "from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)")! as URL)

    // POST and report back with any errors and response codes
    request.httpMethod = "POST"
    let task = session.dataTask(with: request as URLRequest, 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()
}
643ylb08

643ylb083#

requests.post发送一个HTTP POST请求,将键/值对编码为application/x-www-form-urlencoded

q8l4jmvw

q8l4jmvw4#

我花了几个小时试图让选定的答案工作,但无济于事。
虽然我最终能够在一个很大的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路径在Keys.plist中是一个名为mailgunAPIPath的字符串,其值为:

https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?

希望这提供了一个解决方案,任何人都有问题的MailGun和想要避免第3方的解决方案!

xwbd5t1u

xwbd5t1u5#

斯威夫特三号回答:

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

相关问题