swift中的Http POST请求通过Mailjet发送电子邮件

时间:2017-10-13 13:24:56

标签: ios swift mailjet

我尝试使用带有http发布请求的Mailjet API v3发送电子邮件,但我收到错误400.

我在Javascript中使用完全相同的身体并且成功,但我猜错误400与它有关...

有什么想法吗?

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

1 个答案:

答案 0 :(得分:1)

标题错了......

我在做:

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

而不是:

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

使用@LouFranco建议的Charles Proxy,我找到了错误。