[英]Sendgrid sending mail with attachment using web api v3
我是使用 sendgrid web api v3 的新手。 鏈接在這里
現在。 使用 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);
說到要點,您需要通過 curl 請求或 file_get_content 獲取文件內容,然后將該內容編碼為附件->內容參數,請檢查以下對我有用的代碼:
'附件' => [
[
'content' => base64_encode(file_get_contents(config('global.UPLOAD_PATH') . '/my_file.pdf')),
'type' => 'application/pdf',
'filename' => 'my_file.pdf',
'disposition' => 'attachment'
]
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.