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

使用CodeIgniter邮件库时邮件正文显示HTML源码的问题排查

解决CodeIgniter邮件正文显示HTML源码的问题

核心问题:邮件协议配置冲突

你的配置中同时设置了protocol = 'sendmail'和SMTP相关参数(smtp_host、smtp_port等),这会导致配置冲突,mailtype = 'html'的设置无法正确生效。因为当protocol为sendmail时,SMTP的配置项会被忽略,sendmail无法正确解析HTML格式的邮件内容。

修复步骤

1. 修正邮件协议配置

将protocol改为smtp,确保SMTP配置生效,同时补充SMTP所需的换行配置:

$config = array(
    'protocol' => 'smtp', // 改为smtp,与后续SMTP参数匹配
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'xxxxxxxxxx', 
    'smtp_pass' => 'xxxxxxxxxx', 
    'mailtype' => 'html',
    'charset' => 'utf-8',
    'wordwrap' => TRUE,
    'priority' => '1',
    'crlf' => "\r\n", // SMTP要求的标准换行符
    'newline' => "\r\n"
);

2. 确保视图输出未被转义

检查$message变量是否被HTML转义处理(比如用了htmlspecialchars或xss_clean),如果需要保留HTML格式,直接传递原始内容即可,不要额外转义。

3. 验证视图输出内容

可以临时打印视图输出的内容,确认是正确的HTML字符串:

$email_body = $this->load->view('email',$data,true);
var_dump($email_body); // 检查输出是否为未转义的HTML代码
$this->email->message($email_body);

4. 手动指定Content-Type(可选)

如果添加附件后仍有问题,可手动设置邮件的Content-Type头部:

$this->email->set_header('Content-Type', 'text/html; charset=utf-8');

修正后的控制器核心代码片段

$this->load->library('upload');
$config = array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'xxxxxxxxxx', 
    'smtp_pass' => 'xxxxxxxxxx', 
    'mailtype' => 'html',
    'charset' => 'utf-8',
    'wordwrap' => TRUE,
    'priority' => '1',
    'crlf' => "\r\n",
    'newline' => "\r\n"
);
$data['message'] = $message;

$this->load->library('email', $config);

$this->email->from($sendermail, $sendername);
$this->email->to($receivermail);
$this->email->subject($subject);

$email_body = $this->load->view('email', $data, true);
$this->email->message($email_body);

$filename = null;
if (!empty($_FILES['attachment']['name'])) {
    $files = $_FILES['attachment'];
    $config_data['upload_path'] = 'uploads/';
    $config_data['allowed_types'] = 'jpg|jpeg|png';
    $_FILES['attachment']['name'] = time() . '_' . $files['name'];
    $filename = $_FILES['attachment']['name'];
    $_FILES['attachment']['type'] = $files['type'];
    $_FILES['attachment']['tmp_name'] = $files['tmp_name'];
    $_FILES['attachment']['error'] = $files['error'];
    $_FILES['attachment']['size'] = $files['size'];
    
    $this->upload->initialize($config_data);
    if ($this->upload->do_upload('attachment')) {
        $upload_data = $this->upload->data();
        $this->email->attach($upload_data['full_path']);
    }
}

$this->email->send();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:15:40