CodeIgniter危险告警邮件MIME格式显示异常问题求助
问题解决方案
核心原因
你的邮件内容包含HTML标签(<a>链接),但CodeIgniter邮件库默认发送纯文本邮件,同时附件使用URL而非服务器本地路径,导致MIME多部分消息结构混乱,邮件客户端无法正确解析渲染。
具体修复步骤
1. 启用HTML邮件模式
加载邮件库后,明确配置邮件类型为HTML,确保带格式的内容能被正确识别:
$this->load->library('email'); // 初始化邮件配置 $config['mailtype'] = 'html'; $config['charset'] = 'UTF-8'; $this->email->initialize($config);
2. 修正邮件内容格式
将消息内容改为标准HTML结构,修复换行和链接的呈现方式:
$this->email->message('<p>'.$r->userfullname.' 处于危险中。您已被设为授权联系人。</p> <p>其当前经纬度为 '.$r->post_lat.','.$r->post_lng.'。</p> <p><a href="http://maps.google.com/maps?q='.$r->post_lat.','.$r->post_lng.'+('.$address.')&z=14&ll='.$r->post_lat.','.$r->post_lng.'">查看位置</a></p>');
3. 替换附件路径为本地绝对路径
CodeIgniter的attach()方法优先支持服务器本地绝对路径,避免使用URL导致MIME编码异常:
// 获取项目根目录的绝对路径(FCPATH是CodeIgniter内置常量) $base_path = FCPATH . 'assets/danger_images/'; // 替换所有附件引用 $this->email->attach($base_path . $r->img1); $this->email->attach($base_path . $r->img2); $this->email->attach($base_path . $r->img3); $this->email->attach($base_path . $r->img4); $this->email->attach($base_path . $r->img5); $this->email->attach($base_path . $r->audio);
4. 可选:添加纯文本备用内容
为兼容不支持HTML的老旧邮件客户端,可同时设置纯文本版本的消息:
$this->email->set_alt_message($r->userfullname.' 处于危险中。您已被设为授权联系人。 其当前经纬度为 '.$r->post_lat.','.$r->post_lng.'。 查看位置:http://maps.google.com/maps?q='.$r->post_lat.','.$r->post_lng.'+('.$address.')&z=14&ll='.$r->post_lat.','.$r->post_lng);
完整修改后的邮件发送代码片段
$this->load->library('email'); // 初始化邮件配置 $config['mailtype'] = 'html'; $config['charset'] = 'UTF-8'; $this->email->initialize($config); $this->email->from('support@crighter.com', 'Crighter'); $list = array($authemail, $self); $this->email->to($list); $this->email->subject('Danger'); // HTML格式消息内容 $this->email->message('<p>'.$r->userfullname.' 处于危险中。您已被设为授权联系人。</p> <p>其当前经纬度为 '.$r->post_lat.','.$r->post_lng.'。</p> <p><a href="http://maps.google.com/maps?q='.$r->post_lat.','.$r->post_lng.'+('.$address.')&z=14&ll='.$r->post_lat.','.$r->post_lng.'">查看位置</a></p>'); // 纯文本备用消息 $this->email->set_alt_message($r->userfullname.' 处于危险中。您已被设为授权联系人。 其当前经纬度为 '.$r->post_lat.','.$r->post_lng.'。 查看位置:http://maps.google.com/maps?q='.$r->post_lat.','.$r->post_lng.'+('.$address.')&z=14&ll='.$r->post_lat.','.$r->post_lng); // 本地路径加载附件 $base_path = FCPATH . 'assets/danger_images/'; $this->email->attach($base_path . $r->img1); $this->email->attach($base_path . $r->img2); $this->email->attach($base_path . $r->img3); $this->email->attach($base_path . $r->img4); $this->email->attach($base_path . $r->img5); $this->email->attach($base_path . $r->audio); if($this->email->send()) { $data['error'] = false; $data['msg'] = 'Post Submitted'; echo json_encode($data); } else { $data['error'] = true; $data['msg'] = 'Cannot Submit'; echo json_encode($data); }
内容的提问来源于stack exchange,提问作者Shawn Abrahaam
相关产品推荐
相关产品推荐

