php – Sendgrid使用web api v3发送带附件的邮件

我是使用sendgrid web api v3的新手.链接
here

马上.使用api’POST https://api.sendgrid.com/v3/mail/send‘很容易发送一个普通的HTML,但我有这个实例,我们将附加一个文件(csv / xls,pdf),我似乎无法正确.

这是我的代码如下:

我的函数postSendMail

public function postSendMail($data = [])
{
    if ( ! arrayHasValue($data) ) $this->error(__METHOD__, "Data is empty.");

    $request = Curl::to( $this->apiUrl.'mail/send' )        
        ->withHeader('Authorization: Bearer '. $this->apiKey)
        ->withData( $data )
        ->asJson(true)
        ->enableDebug(storage_path('logs/laravel-'.php_sapi_name().'.log'))
        ->post();


    return $request;
}

//my instance
$sendgrid = new Sendgrid;
    $data = [
                'personalizations' => [
                        [
                            'to' => [
                                [ 'email' => 'myemail@gmail.com' ]
                            ],
                            'subject' => 'Hello, World!'
                         ]
                    ],
                'from' => [
                        'email' => 'myemail@gmail.com',
                        'name' => 'my_site'
                    ],
                'content' => [
                        [
                            'type' => 'text',
                            'value' => 'Hello, World!'
                         ]
                    ],
                'track_settings' => [
                        [
                            'click_tracking' => true,
                            'open_tracking' => true
                        ]
                    ],
                'attachments' => [
                        [
                            'content' => base64_encode(config('global.UPLOAD_PATH') . '/my_file.pdf'),
                            'type' => 'application/pdf',
                            'filename' => 'my_file.pdf',
                            'disposition' => 'attachment'
                        ]
                    ]
                ];

    $lists = $sendgrid->postSendMail($data);

邮件已成功发送,但当我查看附件时,它已损坏/无法查看.谁能帮我? 🙁

请帮忙.

最佳答案 问题是您没有将文件读入对象然后编码该对象;你正在编码一个包含文件路径的字符串.

'content' => base64_encode(config('global.UPLOAD_PATH') . '/my_file.pdf')

测试中的所有附件可能大小相同,并且因此小于实际文件.

尝试类似的东西:

$imagedata = file_get_contents(config('global.UPLOAD_PATH') . '/my_file.pdf');
$base64 = base64_encode($imagedata);
点赞