如何在发送电子邮件时使CodeIgniter尊重消息中的换行符

Koe*_*ong 3 codeigniter

如何在尊重消息字段中的换行符的同时使codeigniter发送电子邮件?

表格信息 - http://d.pr/Sae5

<?php echo form_open($this->uri->uri_string()); ?>
<table class="forms-table">
    <tr>
        <td>
            <label for="name">Name</label>
        </td>
        <td>
            <input type="text" id="name" name="name" value="<?php echo set_value('name'); ?>" />
        </td>
        <td>
            <?php echo form_error('name'); ?>
        </td>
    </tr>
    <tr>
        <td>
            <label for="email">Email</label>
        </td>
        <td>
            <input type="text" id="email" name="email" value="<?php echo set_value('email'); ?>" />
        </td>
        <td>
            <?php echo form_error('email'); ?>
        </td>
    </tr>
    <tr>
        <td>
            <label for="message">Message</label>
        </td>
        <td>
            <textarea name="message" id="message" cols="40" rows="6"><?php echo set_value('message'); ?></textarea>

        </td>
        <td>
            <?php echo form_error('message'); ?>
        </td>
    </tr>
    <tr>
        <td colspan="3">
            <input type="submit" value="submit" />
        </td>
    </tr>
</table>
<?php echo form_close(); ?>
Run Code Online (Sandbox Code Playgroud)

当我收到电子邮件时,我会在一行中得到"嗨,我很棒".我有换行符和crlf配置为"\ r \n",charset是"utf-8",我得到我的消息字段的值使用

$message = $this->input->post('message');

...

$this->email->message($message);
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

pun*_*bit 7

为什么不发送电子邮件有HTML?

首先你必须准备好消息(我假设你正在使用POST)

$message = str_replace ("\r\n", "<br>", $this->input->post('message') );
Run Code Online (Sandbox Code Playgroud)

或者您可以使用本机php方式获取 $_POST

$message = str_replace ("\r\n", "<br>", $_POST['message'] );
Run Code Online (Sandbox Code Playgroud)

你所做的,就是用新的线代替 <br>

然后你只需要加载lib并通过config正确设置它,例如:

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

$config['mailtype'] = 'html';
$this->email->initialize($config);


$this->email->from('your@example.com', 'Your Name');
$this->email->to('someone@example.com');

$this->email->subject('Email Test');
$this->email->message( $message );

$this->email->send();
Run Code Online (Sandbox Code Playgroud)

而已!我希望这有帮助,

您可以在http://codeigniter.com/user_guide/libraries/email.html上获得更多信息. 希望您能花时间阅读它!


只需添加,您可以nl2br简单地使用简化此过程->mailtype = 'html';.像这样:

$message = nl2br($this->input->post('message')); // https://codeigniter.com/user_guide/libraries/input.html

$this->load->library('email'); // use autoload.php to remove this line
$this->email->mailtype = 'html';
Run Code Online (Sandbox Code Playgroud)

此外,如果您想创建一个始终使用的配置,您实际上可以创建一个配置文件,CI将自动使用它,因此您永远不需要使用它->initialize.为此,请按照以下简单步骤操作:

  • application\config目录中,创建一个名为email.php的文件
  • 然后你可以简单地在你的配置文件中写入:

`$config['mailtype'] = 'html';`
Run Code Online (Sandbox Code Playgroud)

中提琴!你完成了.就这么简单!现在只需调用您的电子邮件类并像往常一样使用,而无需配置类似的东西mailtype.您可以email config此处查看标题下的完整选项列表.不要忘记,您可以使用application\config\autoload.php自动加载库,从而从代码中删除此行.Email Preferences email$this->load->library('email');