在Swift

时间:2019-03-01 16:41:00

标签: ios json swift mailjet

我正在基于以下代码从html字符串生成PDF数据:https://gist.github.com/nyg/b8cd742250826cb1471f 然后,我得到pdfData并执行此操作:

let base64Data = pdfData.base64EncodedString()
let email = "email@gmail.com"

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

        let body: [String: Any] = [
            "FromEmail": "<...>@gmail.com",
            "FromName": "<...>",
            "Subject": "<...>",
            "Text-part": "<...>",
            "Recipients": recipients,
            "Attachments": [
                "Content-type": "application/pdf",
                "Filename": "file.pdf",
                "content": base64Data
                ]
        ]

        let username_key =  "username_key"
        let password_key = "password_key"
        let loginString = NSString(format: "%@:%@", username_key, password_key)
        let loginData = loginString.data(using: String.Encoding.utf8.rawValue)!
        let base64LoginString = loginData.base64EncodedString()

        var request = URLRequest(url: URL(string: "https://api.mailjet.com/v3/send")!)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("Basic <\(base64LoginString)>", forHTTPHeaderField: "Authorization")

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

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

            if error == nil {
                self.dismiss(animated: true, completion: nil)
            } else {
                // Show error alert
            }
        })
        task.resume()

该代码正在运行,我也在应用程序的其他视图中使用它。问题是电子邮件发送时没有附件。 您能看到问题出在哪里吗? 我还尝试过直接在base64中对html字符串进行编码,然后将其作为.html文件附加到电子邮件中,但是消息仍然没有附件。

1 个答案:

答案 0 :(得分:1)

如果我没看错,则您的“附件”结构错误。在您的代码中,这是一本字典,其中包含三个键值对,分别表示附件的类型,名称和内容。但这应该是包含这三个键值对的对象的列表。

您还为内容类型和内容的键命名错误。 “内容类型”必须为“ ContentType”,“内容”必须为“ Base64Content”。

在这里您可以从mailjet文档中看到一个有效的示例:

"Attachments": [
    {
        "ContentType": "text/plain",
        "Filename": "test.txt",
        "Base64Content": "VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK"
    }
]

所以也许您需要将身体改变为:

let body: [String: Any] = [
    "FromEmail": "<...>@gmail.com",
    "FromName": "<...>",
    "Subject": "<...>",
    "Text-part": "<...>",
    "Recipients": recipients,
    "Attachments": [
        [
            "ContentType": "application/pdf",
            "Filename": "file.pdf",
            "Base64Content": base64Data
        ]
    ]
]

希望我能帮助您!