0

I am trying to connect to Mailgun.com using my credentials. Here is the code:

    let session = URLSession.shared
    var request = URLRequest(url: URL(string:"https://api.mailgun.net/v3/sandboxXXX.mailgun.org/logs")!)
    request.httpMethod = "POST"
    let key = "api:key-XXX"
    request.setValue("Basic \(toBase64(string: key))", forHTTPHeaderField: "Authorization")

    let task = session.dataTask(with: request, completionHandler:{(data, response, error) in
        if let err = error {
            print(err)
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }

    })
    task.resume()

Result: response code = 200 - everything is OK

After I try to connect to mailgun.com/xxx/messages

    let session = URLSession.shared
    var request = URLRequest(url: URL(string:"https://api.mailgun.net/v3/sandboxXXX.mailgun.org/messages")!)
    request.httpMethod = "POST"
    let data = "from=Excited%20User<mailgun@sandboxXXX.mailgun.org>&to=[mail@mail.com]&subject=Hello&text=Testing%20gsome%20Mailgun%20awesomness!"
    let key = "api:key-XXX"
    request.httpBody = data.data(using: .ascii)
    request.setValue("Basic \(toBase64(string: key))", forHTTPHeaderField: "Authorization") 
    let task = session.dataTask(with: request, completionHandler:
    {(data, response, error) in { 
     // the same as above 
    })
    task.resume()

Result: response code = 400 or 401. I have red this: How to send POST parameters in Swift?. I tried to change data many times and string encoding in request.httpBody- without any effect. What should I do to fix that?

Alex
  • 751
  • 1
  • 9
  • 28

1 Answers1

0

Do not use square brackets then it is not necessary (Folks Wisdom) :)

It should be:

let data = "from=Excited%20User<mailgun@sandboxXXX.mailgun.org>
            &to=mail@mail.com //!!! instead of [mail@mail.com] in the original code
            &subject=Hello
            &text=Testing%20gsome%20Mailgun%20awesomness!"
Alex
  • 751
  • 1
  • 9
  • 28