2017-02-07 3 views
-2

Начну с того, что я не PHP-кодер вообще (обычно я использую Coldfusion), однако мне было поручено исправить это для старого проекта.PHP Mail Format

Форма, которая запускает это, отлично работает, и письмо отправляет, однако форматирование отключено. Это PHP, который мы имеем прямо сейчас (contact.php);

<?php 

if ($_POST) { 
$to_Email = "[email protected]"; //Replace with recipient email address 
$subject = 'Contact via Domain'; //Subject line for emails 
//check if its an ajax request, exit if not 
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { 

    //exit script outputting json data 
    $output = json_encode(
      array(
       'type' => 'error', 
       'text' => 'Request must come from Ajax' 
    )); 

    die($output); 
} 

//check $_POST vars are set, exit if any missing 
if (!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userTelephone"]) ||!isset($_POST["userMessage"])) { 
    $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!')); 
    die($output); 
} 

//Sanitize input data using PHP filter_var(). 
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING); 
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL); 
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING); 
$user_Telephone = filter_var($_POST["userTelephone"], FILTER_SANITIZE_STRING); 

//additional php validation 
if (strlen($user_Name) < 4) { // If length is less than 4 it will throw an HTTP error. 
    $output = json_encode(array('type' => 'error', 'text' => 'Name is too short or empty!')); 
    die($output); 
} 
if (!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) { //email validation 
    $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!')); 
    die($output); 
} 
if (strlen($user_Message) < 5) { //check emtpy message 
    $output = json_encode(array('type' => 'error', 'text' => 'Too short message! Please enter something.')); 
    die($output); 
} 

//proceed with PHP email. 
$headers = 'From: ' . $user_Email . '' . "\r\n" . 
     'Reply-To: ' . $user_Email . '' . "\r\n" . 
     'X-Mailer: PHP/' . phpversion(); 

$sentMail = @mail($to_Email, $subject, $user_Message . ' - ' . $user_Name. ' - ' . $user_Telephone, $headers); 

if (!$sentMail) { 
    $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.')); 
    die($output); 
} else { 
    $output = json_encode(array('type' => 'message', 'text' => 'Hi ' .  $user_Name . ' Thank you for your email')); 
    die($output); 
} 
} 
?> 

Письмо, которое отправляется, происходит таким образом;

TST 4 - Test - 123456

Что мне нужно сделать, это изменить его так, это выглядит следующим образом;

Name: tst 4 
Email: [email protected] 
Phone: 123456 

Message: Test 

Линия адресов электронной почты не является критичной, поскольку почта уже прошла через это в поле «от».

Способ отправки этого файла PHP и отправки почты не соответствует ни одному образцу, который я могу найти в Интернете, поэтому меня застряли!

ответ

1

Проблема заключается в третьем параметре, который вы передаете в функцию mail(), которая является содержимым для вашей электронной почты. В настоящее время, вы просто предоставление дефиса отделено списка, так что вы должны создать новую переменную, которая выглядит как ниже:

$email_content = " 
Name: $user_Name 
Email: $user_Email 
Phone: $user_Telephone 

Message: $user_Message"; 

Затем обновить mail() вызов к этому:

$sentMail = @mail($to_Email, $subject, $email_content, $headers); 
+0

Отлично работает, спасибо! – Lee

2

PHP mail() функции :

bool mail (string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]]) 

Последний параметр, заголовки, является необязательным для функции, но необходим для отправки электронной почты HTML, поскольку это где мы можем пройти по объявлению Content-Type, сообщающему почтовым клиентам для анализа электронной почты как HTML.

Content-Type: text/html; charset = UTF-8

Фактически, область заголовков дает нам возможность выполнять множество важных функций электронной почты. Здесь мы можем установить параметры «От:» и «Ответить:», если это необходимо, а также другие получатели CC и BCC.

<?php 

if ($_POST) { 
    $to_Email = "[email protected]"; //Replace with recipient email address 
    $subject = 'Contact via Domain'; //Subject line for emails 
//check if its an ajax request, exit if not 
    if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { 

     //exit script outputting json data 
     $output = json_encode(
      array(
       'type' => 'error', 
       'text' => 'Request must come from Ajax' 
      )); 

     die($output); 
    } 

//check $_POST vars are set, exit if any missing 
    if (!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userTelephone"]) ||!isset($_POST["userMessage"])) { 
     $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!')); 
     die($output); 
    } 

//Sanitize input data using PHP filter_var(). 
    $user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING); 
    $user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL); 
    $user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING); 
    $user_Telephone = filter_var($_POST["userTelephone"], FILTER_SANITIZE_STRING); 

//additional php validation 
    if (strlen($user_Name) < 4) { // If length is less than 4 it will throw an HTTP error. 
     $output = json_encode(array('type' => 'error', 'text' => 'Name is too short or empty!')); 
     die($output); 
    } 
    if (!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) { //email validation 
     $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!')); 
     die($output); 
    } 
    if (strlen($user_Message) < 5) { //check emtpy message 
     $output = json_encode(array('type' => 'error', 'text' => 'Too short message! Please enter something.')); 
     die($output); 
    } 

//proceed with PHP email. 
    $headers = 'From: ' . $user_Email . '' . "\r\n" . 
     'Reply-To: ' . $user_Email . '' . "\r\n" . 
     'X-Mailer: PHP/' . phpversion() . "\r\n" . 
     'Content-Type: text/html; charset=UTF-8\r\n'; 
    $msg = <<<MSG 
Name: {$user_name} <br /> 
Email: {$user_Email} <br /> 
Phone: {$user_Telephone} <br /> <br /> 

Message: {$user_Message} 

MSG; 

    $sentMail = @mail($to_Email, $subject, $msg, $headers); 

    if (!$sentMail) { 
     $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.')); 
     die($output); 
    } else { 
     $output = json_encode(array('type' => 'message', 'text' => 'Hi ' .  $user_Name . ' Thank you for your email')); 
     die($output); 
    } 
} 
?>