2017-06-30 32 views
0

我需要能夠發送一個或多個存儲在Amazon S3服務器上的文件作爲使用SendGrid創建的電子郵件中的附件。PHP:來自S3服務器的SendGrid郵件附件

我遇到的問題是我不是一位web開發專家,而我可以找到的稀疏PHP示例對我沒有多大幫助。

我是否需要將文件從S3服務器下載到本地/ tmp目錄,並將它們作爲附件以這種方式添加,或者我可以從FileController傳遞文件正文並將它作爲附件插入?

我真的不知道從哪裏開始,但這裏是我迄今所做的:

$attachments = array(); 
// Process the attachment_ids 
foreach($attachment_ids as $attachment_id) { 
     // Get the file if it is attached to the Activity 
     if (in_array($attachment_id, $activity_file_ids)) { 
       $file = File::find($attachment_id); 
       $fileController = new FileController($this->_app); 
       $fileObject = $fileController->getFile($attachment_id); 
error_log(print_r($fileObject, true)); 
       $attachment = array(); 
       $attachment['content'] = $fileObject; 
       $attachment['type'] = $fileController->mime_content_type($file->file_ext); 
       $attachment['name'] = explode(".", $file->filename, 2)[0]; 
       $attachment['filename'] = $file->filename; 
       $attachment['disposition'] = "inline"; 
       $attachment['content_id'] = ''; 
     } 
} 

我的下一個步驟將是推$連接陣列到$附件陣列。一旦$附件完成,遍歷它並添加到SendGrid電子郵件對象的每個$附件(電子郵件工作正常,無附件,順便說一句)。

問題是,我不知道我是沿着這條道路走下去,還是有一個更短,更整潔(和工作)的方式呢?

FileController->的GetFile()本質上是做這樣的:

$file = $this->_s3->getObject(array(
    'Bucket' => $bucket, 
    'Key' => $filename, 
)); 
return $file['Body']; 

任何幫助(尤其是代碼示例),將不勝感激!

回答

1

好吧,我已經有了一個可行的解決方案,以現在這樣 - 這裏是代碼:

// Process the attachment_ids 
foreach($attachment_ids as $attachment_id) { 
     // Get the file if it is attached to the Activity 
     if (in_array($attachment_id, $activity_file_ids)) { 
       // Get the file record 
       $file = File::find($attachment_id); 
       // Get an instance of FileController 
       $fileController = new FileController($this->_app); 
       // Set up the Attachment object 
       $attachment = new \SendGrid\Attachment(); 
       $attachment->setContent(base64_encode($fileController->getFile($attachment_id))); 
       $attachment->setType($fileController->mime_content_type($file->file_ext)); 
       $attachment->setFilename($file->filename); 
       $attachment->setDisposition("attachment"); 
       $attachment->setContentId($file->file_desc); 
       // Add the attachment to the mail 
       $mail->addAttachment($attachment); 
     } 
} 

不知道這是否會幫助別人,但它是。解決方案是從S3服務器獲取文件,並將base64_encode($ file ['Body'])傳遞給實例化的Attachment對象的setContent函數,併爲其設置一些其他字段。