2017-08-02 35 views
0

我在我的网站上有一个表单,当我将htmlspecialchars函数添加到php表单处理程序时,似乎我还必须将字符编码更改为utf-8,以便字母与口音会通过。现在我添加了$标题,字符显示正确,但电子邮件($ message)的格式会丢失,并且不换行。这是我的代码如下所示:Php表单处理程序/格式化的电子邮件消息丢失

$surname = htmlspecialchars($_POST["surname"], ENT_COMPAT, 'UTF-8'); 
$firstname = htmlspecialchars($_POST["firstname"], ENT_COMPAT, 'UTF-8'); 
$address = htmlspecialchars($_POST["address"], ENT_COMPAT, 'UTF-8'); 
$age = htmlspecialchars($_POST["age"], ENT_COMPAT, 'UTF-8'); 


$message = " 
Website form: 

Name: " . $firstname . " " . $surname . " 
Address: " . $address . " 
Age: " . $age . "; 


$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type: text/html; charset=UTF-8" . "\r\n"; 

if (mail("[email protected]", $_POST['firstname'] ." ". $_POST['surname'], $message, $headers)) { 
header("Location: ..."); 
} 

我试图用

$message = "Website form\n"; 
$message .= "Name: " . $firstname . " " . $surname . "\n"; 
$message .= "Address: " . $address . "\n"; 
$message .= "Age: " . $age . "\n"; 

解决这个问题,但问题仍然存在。我也尝试将内容类型更改为纯文本,但电子邮件消息以附件形式出现。由于格式化仍然丢失,我无所适从,不知道自己做错了什么。我是一个初学者与PHP,所以任何帮助将不胜感激。

回答

0

你应该尝试消息格式是这样的:

// email message 
$message =""; 
$message .= 'Website Form:'."\r\n"; 
$message .= 'Name:'. $firstname ." ". $surname . "\r\n"; 
$message .= 'Address:'. $address . "\r\n"; 
$message .= 'Age:'. $age . "\r\n"; 

下面是完整的代码:

<?php 
$surname = htmlspecialchars($_POST["surname"], ENT_COMPAT, 'UTF-8'); 
$firstname = htmlspecialchars($_POST["firstname"], ENT_COMPAT, 'UTF-8'); 
$address = htmlspecialchars($_POST["address"], ENT_COMPAT, 'UTF-8'); 
$age = htmlspecialchars($_POST["age"], ENT_COMPAT, 'UTF-8'); 

$to = '[email protected]'; 
$subject = 'Subject Line'; 
$from = '[email protected]'; 

// To send HTML mail, the Content-type header must be set 
$headers = 'MIME-Version: 1.0' . "\r\n"; 
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; 

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

// email message 
$message = ""; 
$message .= 'Website Form:'."\r\n"; 
$message .= 'Name:'. $firstname ." ". $surname . "\r\n"; 
$message .= 'Address:'. $address . "\r\n"; 
$message .= 'Age:'. $age . "\r\n"; 

// Sending email 
if(mail($to, $subject, $message, $headers)){ 
    echo 'Your mail has been sent successfully.'; 
} else{ 
    echo 'Unable to send email. Please try again.'; 
} 
?> 
相关问题