【问题标题】:Sendgrid attachment resource not found未找到 Sendgrid 附件资源
【发布时间】:2020-04-15 19:05:34
【问题描述】:

电子邮件是从相同的代码发送的,现在我在添加附件代码后从 sandgrid api 收到“找不到资源”错误,“sendgrid/sendgrid”:“~6.0”和“laravel/framework”:“5.4.* ",

$from = new SendGrid\Email($data['from_name'], $data['from']);
$subject = $data['subject'];
$to = new SendGrid\Email("user","user.name@domain.name");

$content = new SendGrid\Content("text/html", $data['view']);

$mail = new SendGrid\Mail($from, $subject, $to, $content);

$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail();

//Attachment code start
if(isset($data['attach_files']) && is_array($data['attach_files']) && count($data['attach_files'])>=1){
    foreach($data['attach_files'] as $attach_files_i=>$attach_files_path){
        $filename = basename($attach_files_path);
        $file_encoded = base64_encode(file_get_contents($attach_files_path));
        //echo '<pre>--$filename';print_r($filename);echo '</pre>'; //working fine
        //echo '<pre>--$file_encoded';print_r($file_encoded);echo '</pre>'; //working fine
        //echo '<pre>--mime_content_type($attach_files_path)';print_r(mime_content_type($attach_files_path));echo '</pre>'; //working fine
        $attachment = new SendGrid\Attachment();
        $attachment->setType(mime_content_type($attach_files_path));
        $attachment->setContent($file_encoded);
        $attachment->setDisposition("attachment");
        $attachment->setFilename($filename);
        $response->addAttachment($attachment);
    }
}
//Attachment code end

$response = $response->send()->post($mail);

echo "<pre>"; print_r($response); die;

来自 sendgrid 的响应

SendGrid\Response Object
(
    [statusCode:protected] => 404
    [body:protected] => {"errors":[{"field":null,"message":"resource not found"}]}
    [headers:protected] => Array
        (
            [0] => HTTP/1.1 404 NOT FOUND
            [1] => Server: nginx
            [2] => Date: Wed, 15 Apr 2020 18:43:55 GMT
            [3] => Content-Type: application/json
            [4] => Content-Length: 58
            [5] => Connection: keep-alive
            [6] => 
            [7] => 
        )

)

【问题讨论】:

    标签: php laravel sendgrid


    【解决方案1】:

    这可能是使用错误的类命名空间

    使用这个命名空间

    use SendGrid\Mail\Attachment;
    

    【讨论】:

      【解决方案2】:

      错误是删除函数 base64_encode

      $attachment = new \SendGrid\Attachment();
      $attachment->setContent(file_get_contents($attach_files_path));
      $attachment->setType(mime_content_type($attach_files_path));
      $attachment->setFilename($filename);
      $attachment->setDisposition("attachment");
      $mail->addAttachment($attachment);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-30
        • 2013-06-22
        • 1970-01-01
        相关资源
        最近更新 更多