当有换行符时,CRLF(\ r \ n)会在电子邮件中显示

时间:2016-01-02 22:24:17

标签: php email

我不确定我在这里做错了什么。在电子邮件中,\r\n会在每次换行时都会显示。如何修改代码来修复它?

public function sendSupportEmail($email, $name, $comments)
{
    // Wait until Google Apps are configured to accept from this domain
    //$to = "test@mail.com";
    $to = "test@mail.com.com";
    $subject = "Support: Support Inquiry";

    // Headers
    // To send HTML mail, you can set the Content-type header.
    $autoHeaders  = "MIME-Version: 1.0\r\n";
    $autoHeaders .= "Content-type: text/html; charset=iso-88591\r\n";
    $autoHeaders .= "From: Web Bot";
    $autoHeaders .= "<webbot@mail.com>\r\n";
    $autoHeaders .= "Reply-To: webbot@mail.com\r\n";
    $autoHeaders .= "Return-Path: webbot@mail.com\r\n";
    $autoHeaders .= "X-Mailer: PHP 5.x\r\n";

    // Print the local date
    $date = new DateTime('now', new DateTimeZone('America/Denver'));
    $datePrint = $date->format('F j, Y, g:i a');

    // Create Text Based Message Below
    $message = "<h3>Support Inquiry sent on {$datePrint}</h3>";
    $message .= "<b>Name:</b><br>{$name}<br><br>";
    $message .= "<b>Email:</b><br><a href='mailto:{$email}'>{$name}</a><br><br>";
    $message .= "<b>Comments:</b><p>{$comments}</p>";

    // Send them the E-Mail
    return mail($to, $subject, $message, $autoHeaders);
}

2 个答案:

答案 0 :(得分:4)

这里使用的理想函数是PHP的nl2br()函数。

并在任何地方使用textarea输入(或其他输入/变量)。这已在注释中建立,这就是您用于注释表单元素的内容。

I.e。:并假设您的表单元素被命名为“comments”并使用POST方法,因为我们不知道它是什么,或者$comments被指定为何处。这不在您的问题中,因此我提交以下内容作为可能的解决方案。

$comments = $_POST['comments'];
$comments = nl2br($comments);

或者,一气呵成:

$comments = nl2br($_POST['comments']);
  • 如果需要,分别修改。

答案 1 :(得分:1)

当您发送HTML电子邮件时,您需要将\ r \ n替换为&lt; br&gt;在电子邮件正文中。

在返回邮件之前,你应该使用php的str_replace函数,如下所示。

.........
.........
$message .= "<b>Comments:</b><p>{$comments}</p>";
$message = str_replace("\r\n", "<br>", $message); 
// Send them the E-Mail
return mail($to, $subject, $message, $autoHeaders);