我正在尝试将文件附加到Mailgun。这是我的curl命令:
curl -s --user 'api:key-XXX'
https://api.mailgun.net/v3/sandbox---.mailgun.org/messages
-F from='Excited User<[email protected]>'
-F [email protected]
-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<[email protected]>",
"to": "[email protected]",
"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)
}
结果相同:附件尚未附加到邮件中。
在这种情况下如何将文件附加到邮件?
对于仍然在这方面工作的人。似乎MailGun API在每个包含的附件中查找要附加的名称,因此这一行:
multipartFormData.append(imageData!, withName: "domru", fileName: "domru.jpeg", mimeType: "image/jpeg")
需要改为:
multipartFormData.append(imageData!, withName: "attachment", fileName: "domru.jpeg", mimeType: "image/jpeg")
不确定是否完全修复它