【问题标题】:Send attachment email with php and sendgrid使用 php 和 sendgrid 发送附件电子邮件
【发布时间】:2018-01-09 13:29:14
【问题描述】:

我想用 Sendgrid 发送一封电子邮件,使用 cURL。这是我已经使用了一段时间的工具,当我想发送一封简单的电子邮件时,一切都很好。

但是现在,我正在尝试将附件文件与电子邮件一起发送。发生的情况是我在电子邮件中看到了该文件,但它显示为只有 1KB 大小,并且无法下载该文件。

我在想这可能是一个路径问题。我尝试的路径(假设 PHP 文件位于地址 mywebsite.com/file.php)如下:

我也尝试将平台的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,这对我来说似乎是正确的。

标签: php email curl sendgrid


【解决方案1】:

我找到了一个解决方案,它可能不是最佳的,但至少有效。

替换'files['.$fileName.']' =&gt; '@'.$filePath.'/'.$fileName

'files['.$fileName.']' =&gt; file_get_contents($filePath.'/'.$fileName)

我对复制 Sendgrid API 的文档不起作用感到有点惊讶,但也许有一个更干净的解决方案可以使用它。如果是这样,请随时分享(例如,不要对我的帖子投反对票)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多