【发布时间】:2018-01-09 13:29:14
【问题描述】:
我想用 Sendgrid 发送一封电子邮件,使用 cURL。这是我已经使用了一段时间的工具,当我想发送一封简单的电子邮件时,一切都很好。
但是现在,我正在尝试将附件文件与电子邮件一起发送。发生的情况是我在电子邮件中看到了该文件,但它显示为只有 1KB 大小,并且无法下载该文件。
我在想这可能是一个路径问题。我尝试的路径(假设 PHP 文件位于地址 mywebsite.com/file.php)如下:
- 'http://www.mywebsite.com/documents'(一个网址)
- '文件'
- '文件/'
- '/文档'
- '/documents/'
我也尝试将平台的URL直接输入到文件路径参数中。
我从 Sendgrid API 获得的响应是{"message":"success"}。
我关注this guide,代码如下:
PHP
$html = '<p>Hello StackOverflow</p>';
$fileName = 'myDocument.pdf';
$filePath = 'http://mywebsite.com/documents'
$url = 'https://api.sendgrid.com/';
$user = [MY_USER];
$pass = [MY_PASS];
$js = array(
'sub' => array(':name' => array([MY_FIRSTNAME])),
);
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => $to,
'subject' => $subject,
'html' => $html,
'from' => $from,
'fromname' => [MY_FROMNAME],
'x-smtpapi' => json_encode($js),
'files['.$fileName.']' => '@'.$filePath.'/'.$fileName
);
print_r($params); // AT THAT POINT, WHAT IS PRINTED IS EXACTLY WHAT I EXPECT
$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);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
【问题讨论】:
-
$filePath = 'http://mywebsite.com/documents'如果这是您的实际语法,则有两个原因是错误的。 1) 它是 URL 而不是路径。 2)它缺少关闭。错误报告会告诉你。 -
这不是我的实际语法。但是如果你查看 $param 变量,你会得到@mywebsite.com/documents/myDocument.pdf,这对我来说似乎是正确的。