Swift Send Email with MailGun

后端 未结 4 1649
时光说笑
时光说笑 2021-01-15 01:20

Problem

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

Research So Far

As I understa

4条回答
  •  没有蜡笔的小新
    2021-01-15 01:45

    I spent hours trying to get the selected answer working, but to no avail.

    Although I was finally able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.

    // 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@.com%3E&to=reservations@.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()
    }
    

    The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:

    https://API:key-@api.mailgun.net/v3/.com/messages?
    

    Hope this offers a solution to anyone else having issues with MailGun and wanting to avoid a 3rd party solution!

提交回复
热议问题