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

如何在CodeIgniter的SMTP函数中给两个收件人发送不同内容的邮件

在CodeIgniter中同一函数发送两封不同内容的SMTP邮件

没问题,这个需求其实很好解决!CodeIgniter的Email类在发送完一封邮件后,会保留之前的配置参数,所以你只需要先清空原有配置,再重新设置第二封邮件的参数就可以啦。

核心解决方法:使用$this->email->clear()

这个方法会重置Email类里的所有收件人、主题、内容等参数(默认也会清空附件,如果你有附件需要保留,可以传FALSE参数,比如$this->email->clear(FALSE))。

修改后的完整代码

public function send_cita_from_out() { 
    $config = Array( 
        'protocol' => 'smtp', 
        'smtp_host' => 'xxxxx', 
        'smtp_port' => 25, 
        'smtp_user' => 'xxxxx', // 替换为你的SMTP账号
        'smtp_pass' => 'xxxx', // 替换为你的SMTP密码
        'mailtype' => 'html', 
        'charset' => 'iso-8859-1', 
        'wordwrap' => TRUE 
    ); 

    $name = $this->input->post('name'); 
    $id= $this->input->post('id'); 
    $date= $this->input->post('date'); 
    $tel = $this->input->post('tel'); 
    $email= $this->input->post('email'); 

    // 第一封邮件的内容
    $data = " <html> <body> <p><strong>NAME</strong> : $name </p> <p><strong>ID</strong>: $id</p> <p><strong>DATE</strong> : $date</p> </body> </html>"; 

    // 加载Email库并配置基础参数
    $this->load->library('email', $config); 
    $this->email->set_newline("\r\n"); 
    $this->email->set_mailtype("html"); 
    $this->email->from($email); 

    // 发送第一封邮件给管理员/指定收件人
    $this->email->to('xxxxxxx@gmail.com');// 替换为第一收件人邮箱
    $this->email->subject('用户提交的预约信息'); 
    $this->email->message($data); 

    $send_first = $this->email->send();

    // 清空原有邮件配置,准备发送第二封
    $this->email->clear();

    // 配置第二封邮件的专属参数
    $this->email->to($email); // 发送给提交表单的用户
    $this->email->subject('感谢您提交预约信息'); 
    $this->email->message("Thank you for sending your info. We will contact you soon!"); 

    $send_second = $this->email->send();

    // 检查两封邮件的发送状态
    if($send_first && $send_second) { 
        echo '两封邮件都已成功发送.'; 
    } else { 
        // 输出对应错误信息
        if (!$send_first) show_error($this->email->print_debugger());
        if (!$send_second) show_error($this->email->print_debugger());
    } 
}

关键注意事项

  • $this->email->clear()一定要在第一封邮件发送完成后调用,不然会清空第一封的配置,导致第一封发送失败。
  • 第二封邮件的from如果和第一封一致,可以不用重新设置;如果需要换发件人,记得重新调用$this->email->from()。
  • 如果你需要发送更多邮件,只需要重复“清空配置→设置新参数→发送”的流程即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:06:12