【问题标题】:Codeigniter email library sending blank emails or html source codeCodeigniter 电子邮件库发送空白电子邮件或 html 源代码
【发布时间】:2018-12-29 18:46:24
【问题描述】:

我以前通过 CodeIgniter 发送电子邮件从来没有遇到过问题,但突然之间,我的最新项目出现了问题。

我使用这个mail server tool 在我的本地主机上发送邮件,这之前从未给我带来任何问题,然后是 CodeIgniter 电子邮件库。

我可以得到以下两种结果之一: 电子邮件发送,但显示所有原始 HTML 源代码,或者电子邮件发送并有主题行,但整个正文为空白。

这是我的email_helper.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

function send_email($to, $subject, $template)
{
    $ci = &get_instance();
    $ci->load->library('email');

    $config = array(
      'mailtype'  => 'html',
      'newline' => '\r\n',
      'crlf'  => '\r\n'
    );

    //If I comment out this line, it sends raw HTML, otherwise it sends a blank body.
    $ci->email->initialize($config);

    $ci->email->from($ci->config->item('from_email_address'), $ci->config->item('from_email_name'));
    $ci->email->reply_to($ci->config->item('from_email_address'), $ci->config->item('from_email_name'));
    $ci->email->to($to);

    $ci->email->subject($subject);
    $ci->email->message($ci->load->view('email/' . $template . '_html', $data, TRUE));
    $ci->email->send();
}

这是我的test_html.php

<!DOCTYPE html>
<html>
  <head><title>Test</title></head>
  <body>
      <div style="max-width: 800px; margin: 0; padding: 30px 0;">
       TEST!
      </div>
  </body>
</html>

然后我从我的控制器调用电子邮件助手:

$this->load->helper('email_helper');
send_email($this->input->post('email'), 'Test Subject', 'test');

【问题讨论】:

  • 尝试不使用 doctype 并最终使用 head 标签
  • 不幸的是没有用。

标签: php codeigniter email codeigniter-3 codeigniter-email


【解决方案1】:

希望对您有所帮助:

您在加载视图部分中缺少$data,还尝试使用$ci-&gt;load-&gt;library('email', $config); 而不是$ci-&gt;email-&gt;initialize($config);

send_email 应该是这样的:

function send_email($to, $subject, $template)
{
    $ci = & get_instance();

    $config = array(
      'mailtype'  => 'html',
      'charset' => 'iso-8859-1',
      'newline' => '\r\n',
      'crlf'  => '\r\n'
    );

    $data = '';

    $body = $ci->load->view('email/' . $template . '_html', $data, TRUE);
    echo $body; die;

    $ci->load->library('email', $config);
    $ci->email->set_mailtype("html");
    $ci->email->from($ci->config->item('from_email_address'), $ci->config->item('from_email_name'));
    $ci->email->reply_to($ci->config->item('from_email_address'), $ci->config->item('from_email_name'));
    if ($to) 
    {
      $ci->email->to($to);

      $ci->email->subject($subject);
      $ci->email->message($body);
      if ($ci->email->send())
      {
        return TRUE;
      }
      else
      {
        echo $ci->email->print_debugger();die;
      }
    }
}

更多:https://www.codeigniter.com/user_guide/libraries/email.html

【讨论】:

  • 没有任何错误,发送成功,但是body还是空白。
  • echo $body; die;时你会得到什么
  • 在 chrome 开发工具中,当我回显正文时,我可以看到呈现的 HTML。所以这件作品似乎工作正常。
  • ok 尝试在$ci-&gt;email-&gt;to($to);之前添加这个$ci-&gt;email-&gt;set_mailtype("html");
  • 成功了!我简直不敢相信!为什么在配置数组中设置mailtype时不起作用,但它会直接起作用?可能是 CI 邮件类中的错误?