Search code examples
iosswiftmailjet

Http POST request in swift to send an email via Mailjet


I'm trying to send an email with the Mailjet API v3 with a http post request but I'm getting an error 400.

I used the exact same body with success in Javascript, but I guess the error 400 is related with it...

Any ideas ?

var recipients = [Any]()
recipients.append(["Email": "email@gmail.com"])

var body: [String: Any] = [
  "FromEmail": "anEmail@gmail.com",
  "FromName": "Me",
  "Subject": "YEEES",
  "Text-part": "Greetings from IOS ;)",
  "Recipients": recipients
]

var request = URLRequest(url: self.apiURL)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("Authorization", forHTTPHeaderField: "Basic <keysInBase64>")

    do {
      request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
    }
    catch {
      print("error during JSON serialization")
      dump(error)
      return
    }

let session = URLSession.shared
    let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
      print(error)
      print(response)
      print(data)
    })
    task.resume()

Solution

  • Headers was wrong...

    I was doing :

    request.setValue("Authorization", forHTTPHeaderField: "Basic <keysInBase64>")
    

    Instead of :

    request.setValue("Basic <keysInBase64>", forHTTPHeaderField: "Authorization")
    

    Using the Charles Proxy as suggested by @LouFranco, I was able to find the mistake.