**Problem**

I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app.

**Research So Far**

As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) 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](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). 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](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift)

**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": ["bar@example.com", "(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!
['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/']
people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and 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()
}

```
Swift 3 answer:

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

```