我在我的网站上有一个表单,当我向php表单处理程序添加htmlspecialchars函数时,似乎我还必须将字符编码更改为utf-8,以便带有重音的字母会通过。现在我已经添加了$ header,字符显示正确,但电子邮件消息($ message)的格式丢失,没有换行符。这就是我的代码:
$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("me@me.com", $_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";
但问题仍然存在。我还尝试将内容类型更改为text / plain,但电子邮件消息显示为附件文件。我不知所措,因为格式化仍然丢失,我不知道自己做错了什么。我是php的初学者,所以任何帮助都会受到赞赏。
答案 0 :(得分: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 = 'youemail@email.com';
$subject = 'Subject Line';
$from = 'info@example.com';
// 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.';
}
?>