You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SendGrid inbound parse处理入站邮件时如何获取附件内容

SendGrid Inbound Parse 附件处理方案

核心逻辑

SendGrid 入站解析回调的POST请求中,每个附件的实际二进制内容会以attachmentX(X为从1开始的正整数)为参数名直接提交,和attachment-info返回的元数据键一一对应,无需额外调用接口拉取。

前置检查项

  • 确认PHP配置的post_max_size、upload_max_filesize参数值大于你需要接收的最大附件总大小,避免附件内容被截断
  • 提前创建附件存储目录并配置读写权限

修改后的参考代码

$html = $_POST['html'];
$recipient = $_POST['to'];
$subject = $_POST['subject'];
$envelope = json_decode($_POST['envelope']);
$sender = $envelope->from;
$user = -1;
$created_at = date('Y-m-d H:i:s');
$attachments = $_POST['attachments'];
$attachmentPaths = []; // 存储附件信息,后续可关联邮件存入数据库

if($attachments > 0)
{
    $attachment_info = json_decode($_POST['attachment-info'], true);
    // 自定义附件存储目录,需确保目录有可写权限
    $saveDir = __DIR__ . '/email_attachments/';
    if(!is_dir($saveDir)){
        mkdir($saveDir, 0755, true);
    }
    
    for($i = 1; $i <= $attachments; $i++)
    {
        $fileMeta = $attachment_info['attachment'.$i];
        // 直接获取附件二进制内容
        $fileContent = $_POST['attachment'.$i];
        // 生成唯一文件名避免重名覆盖
        $saveFileName = uniqid() . '_' . $fileMeta['filename'];
        $saveFullPath = $saveDir . $saveFileName;
        // 写入本地文件
        file_put_contents($saveFullPath, $fileContent);
        // 组装附件信息留用
        $attachmentPaths[] = [
            'original_filename' => $fileMeta['filename'],
            'save_path' => $saveFullPath,
            'mime_type' => $fileMeta['type'],
            'content_id' => $fileMeta['content-id'] ?? ''
        ];
    }
}

$params = [
    'type' => 'email',
    'customer_id' => get_customer($sender),
    'direction' => 'in',
    'sender' => $sender,
    'recipient' => $recipient,
    'subject' => $subject,
    'message' => $html,
    'status' => 'delivered',
    'user' => 0,
    // 可将附件信息序列化后存入此字段,或者单独创建附件表关联邮件ID
    'attachments' => json_encode($attachmentPaths)
];

//process email
//this stores email into DB
process_email($params);

附加说明

  • 如果需要实现附件在线预览,将存储目录配置到站点的公共可访问目录下,为每个附件生成对应的HTTP访问链接存入数据库即可
  • 建议定期清理无用附件,避免占用过多服务器存储空间

内容的提问来源于stack exchange,提问作者joanb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:48:03