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

CodeIgniter 4邮件发送成功但附件未随邮件发出问题求助

解决邮件附件未发送问题

针对PDF生成成功但邮件未携带附件的情况,可按以下步骤排查修复:

1. 修正文件路径处理逻辑

你用underscore()处理了完整文件路径,这个函数会把空格、特殊字符转成下划线,但容易破坏路径结构:

  • Windows系统下的路径分隔符\可能被转义或处理错误,建议统一用正斜杠/
  • 完整路径被underscore()处理后,可能和实际生成的文件路径不匹配

建议只对文件名部分使用underscore(),保留路径结构:

// 单独处理文件名,路径保持原始结构
$fileName = underscore("invoice {$invoice_number}.pdf");
$pdfFileName = WRITEPATH . 'uploads/' . $fileName;
file_put_contents($pdfFileName, $dompdf->output());

可以先输出$pdfFileName的值,确认路径和实际生成的文件完全一致。

2. 完善邮件附件参数配置

CodeIgniter的attach()方法支持指定附件显示名称和MIME类型,明确配置这些参数能避免识别问题:

// 替换原attach代码,指定附件类型和显示名称
$email->attach($pdfFileName, 'attachment', "Invoice_{$invoice_number}.pdf", 'application/pdf');

3. 捕获邮件发送错误信息

添加错误捕获代码,直接查看发送过程中的报错细节,快速定位问题:

if (!$email->send()) {
    echo $email->printDebugger();
    exit;
}

4. 检查邮件配置正确性

如果使用SMTP发送邮件,确保Config/Email.php中的SMTP参数(SMTPHost、SMTPUser、SMTPPass、SMTPPort)配置正确,部分邮箱服务商(如Gmail)需要开启App密码或允许低安全性应用访问。

修改后的完整代码示例

helper('inflector');

// 拆分路径与文件名处理,避免路径被破坏
$fileName = underscore("invoice {$invoice_number}.pdf");
$pdfFileName = WRITEPATH . 'uploads/' . $fileName;
file_put_contents($pdfFileName, $dompdf->output());

if (file_exists($pdfFileName) && is_readable($pdfFileName)) {
    $email = \Config\Services::email();       

    $email->setFrom('satechs.solutions@gmail.com', 'SaTechs Solutions');
    $email->setTo($data['bill_to']);
    $email->setSubject('Invoice for ' . $invoice_number);
    $email->setMessage('<h3> Dear ' . $data['clientname'] . ',</h3>' . '<br>' . 'Please find the attached invoice that is due on: ' . $data['due_date']. '.');
    // 指定附件相关参数
    $email->attach($pdfFileName, 'attachment', "Invoice_{$invoice_number}.pdf", 'application/pdf'); 
    
    // 捕获发送错误
    if (!$email->send()) {
        echo $email->printDebugger();
        exit;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:23:08