Search code examples
swiftapiswift2mailgun

Swift Send Email with MailGun


Problem

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

Research So Far

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

Code

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.

Question

How do I do that in Swift?

Thanks!


Solution

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

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

    This is a working code:

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