I'm trying to send an email using mailgun on an iOS app with Swift. Lack of security aside, I always get a 400
Error. If I change a bit the key, I get a 401
so authentication works.
Whether I use Alamofire:
let parameters = ["Authorization" : "api:key-...",
"from": "from@email.com",
"to": "to@email.com",
"subject": "Test",
"text": "Testing email"]
alamofireManager.request("https://api.mailgun.net/v3/sandbox...mailgun.org/messages", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil)
.authenticate(user: "api", password: "key-...")
.validate(statusCode: 200 ..< 300)
.validate(contentType: ["application/json"])
.responseJSON { response in
print(response)
print("Response : \(response.error)")
}
Or NSMutableURLRequest:
let session = URLSession.shared
let request = NSMutableURLRequest(url: URL(string: "https://api.mailgun.net/v3/sandbox...mailgun.org/messages")!)
request.httpMethod = "POST"
let credentials = "api:key-..."
request.setValue("Basic \(Data(credentials.utf8).base64EncodedString())", forHTTPHeaderField: "Authorization")
let data = "from:Test<(test@test.com)>&to:[my_email_address@gmail.com,(my_email_address@gmail.com)]&subject:Hello&text:Testing_email"
request.httpBody = data.data(using: String.Encoding.ascii)
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()
I always get a 400
. I don't see what's wrong in my parameters. Any idea?