PHP:来自S3服务器的SendGrid邮件附件

问题描述:

我需要能够发送一个或多个存储在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']; 

任何帮助(尤其是代码示例),将不胜感激!

好吧,我已经有了一个可行的解决方案,以现在这样 - 这里是代码:

// 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函数,并为其设置一些其他字段。