SendGrid - 卷曲php外部文件附件损坏
问题描述:
我正在使用SendGrid进行卷曲方法的客户项目。SendGrid - 卷曲php外部文件附件损坏
所有工作正常,但我的电子邮件与SendGrid发送附加(ir)文件(s)被打破。
这里是我的代码:
$documentList = array(
"DOC1.php" => "http://www.customerdomain.com/my/path/where/my/attachment/file/is/myfile.pdf"
);
$params = array(
'api_user' => $user;
'api_key' => $pass,
'x-smtpapi' => json_encode($json_string),
'from' => $from,
'to' => $to,
'subject' => $subject,
'html' => $mailHtml,
'text' => $mailText
);
if(count($documentList)>0){
foreach($documentList as $fileName=>$documentPath){
$params['files['.$fileName.']'] = $documentPath;
}
}
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
当我没有在我的阵列的关键扩展文件,我已经包含了相关值的文本文件。
我觉得我并不孤单有这个问题,好吧,如果你有任何想法解决这个问题,谢谢你的帮助!
答
您遇到的问题是因为您为SendGrid提供了文件的URL而不是文件本身,并且SendGrid的API需要该文件。
为了让您的代码工作,只需将$documentList
变量更改为:
$documentList = array(
"DOC1.pdf" => "@" . realpath("/path/where/my/attachment/file/is/myfile.pdf")
);
说明对这种文件上传可以在this StackOverflow Question随处可见,但是,否则你可能想使用curl_file_create,要做到这一点。
然而,或许要做到这一点的最好/最简单的方法是使用SendGrid's PHP Library这使得sending attachments, trivially simple.:
require("path/to/sendgrid-php/sendgrid-php.php");
$sendgrid = new SendGrid('username', 'password');
$email = new SendGrid\Email();
$email->addTo('[email protected]')->
setFrom('[email protected]')->
setSubject('Subject goes here')->
setText('Hello World!')->
setHtml('<strong>Hello World!</strong>')
addAttachment("../path/to/file.txt");
$sendgrid->send($email);
答
我最初的问题是,因为路径是自动生成的链接,这就是为什么我没有使用url而不是真实路径。
无论如何,我改变了我的代码,现在使用文件realpath(和@之前)后提到的mimetype的实时路径。
现在看起来很好。
我想感谢您的帮助。
Regards
'curl_file_create' working for me – Shahbaz 2016-11-06 19:19:14