使用swift将文件上传到mailgun服务器

时间:2017-12-05 11:23:44

标签: swift alamofire mailgun

我正在尝试将文件附加到Mailgun。这是我的curl命令:

curl -s --user 'api:key-XXX'
https://api.mailgun.net/v3/sandbox---.mailgun.org/messages     
-F from='Excited User<mailgun@sandbox---.mailgun.org>'     
-F to=mail@gmail.com     
-F subject='Hello'     
-F text='Testing some Mailgun awesomness!' 
-F attachment='@/Users/.../mytestfile.jpeg'

结果:好的,该文件已附加到邮件中并已成功传输。

之后,我尝试使用URLRequest

    guard let filePath = Bundle.main.url(forResource: "domru", withExtension: "jpeg") else {
        print(">>>can't find path")
        return
    }      
    let parameters: HTTPHeaders = [
        "from": "Excited User<mailgun@sandbox---.mailgun.org>",
        "to": "mail@gmail.com",
        "subject": "hello",
        "text": "my text message" ]

    let data = encodeRequest(parameters: parameters, attachment: filePath)
    var request = URLRequest(url: URL(string:"https://api.mailgun.net/v3/sandbox---.mailgun.org/messages")!)
    request.httpMethod = "POST"
    request.httpBody = data.data(using: .utf8)
    request.addValue("Basic \(credentialData!)", forHTTPHeaderField: "Authorization")
    let task = URLSession.shared.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()

    private func encodeRequest(parameters:[String:String], attachment: URL) -> String {
    var result = ""
    for (key, value) in parameters {
        result.append("\(key)="+"\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! + "&")
    }
    result.append("attachment="+attachment.path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)
    return result
    }

结果:邮件的文本已发送,但文件尚未附加。

我也尝试用Alamofire解决这个问题:

    let imageData = UIImageJPEGRepresentation(UIImage(named:"domru.jpeg")!, 1)

    let header : HTTPHeaders = ["Authorization":"Basic \(credentialData!)"]

    Alamofire.upload(
        // parameters are the same as in the previous part of code
        multipartFormData: { (multipartFormData) in
            for (key, value) in parameters {
                    multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
            }
            multipartFormData.append(imageData!, withName: "domru", fileName: "domru.jpeg", mimeType: "image/jpeg")
        },
        to: "https://api.mailgun.net/v3/sandbox---.mailgun.org/messages",
        method: .post,
        headers: header,
        encodingCompletion: { (result) in
            debugPrint(result)
        }

结果相同:附件尚未附加到邮件中。

在这种情况下如何将文件附加到邮件中?

1 个答案:

答案 0 :(得分:1)

对于仍在从事此工作的任何人。似乎MailGun API在包含的每个附件中都查找要作为附件的名称,因此此行:

multipartFormData.append(imageData!, withName: "domru", fileName: "domru.jpeg", mimeType: "image/jpeg")

需要更改为:

multipartFormData.append(imageData!, withName: "attachment", fileName: "domru.jpeg", mimeType: "image/jpeg")

不确定是否可以完全解决