【发布时间】:2012-01-13 00:51:34
【问题描述】:
我有这个简单的联系表格:
<form id="emailForm" action="contact.php" method="POST">
<label for="name">Your name</label>
<input type="text" id="name" name="name">
<label for="email">Your email</label>
<input type="text" id="email" name="email">
<label for="subject">Subject</label>
<input type="text" id="subject" name="subject">
<label for="message">Message</label>
<textarea id="message" name="message"></textarea>
<p class="emailPop" id="emailError"></p>
<input id="submit" type="submit" value="Send">
</form>
如果邮件包含像 àèìòù 这样的 unicode 字符,当我收到包含我已发送的邮件的电子邮件时,它们会以奇怪的方式显示,例如 à à à ùòèòòòèà èà à ò。
我将表单摘录到仅包含表单的页面,并且来自该页面的消息未经修改就到达了我的电子邮件。经过一番试验,我发现问题的原因是标签<meta charset="utf-8">,它实际上应该让事情正常进行。
由于其他页面使用 unicode 字符,我不能没有这个标签,但它会与我的表单输出冲突。我该怎么办?
这是负责发送电子邮件的 php 脚本的代码
<?php
//require_once 'Mail.php';
function exit_message($error) {
echo json_encode(array('status' => 'error', 'message' => $error));
exit();
}
$data = $_POST;
// Check that all fields are filled in
$fields = array('name', 'email', 'subject', 'message');
foreach($fields as $field) {
if(empty($data[$field]))
exit_message("Please insert your " . $field . '.');
}
// Check if email is valid
if(!filter_var($data['email'], FILTER_VALIDATE_EMAIL))
exit_message('The email you provided is invalid.');
// Check if message is longer than 9 characters
if(strlen($data['message']) <= 9)
exit_message('Please write a message at least 9 characters long.');
// Begin composing the message
$message = array(
'recipient' => 'xxxxxxx@gmail.com',
'subject' => $data['subject'],
'body' => stripslashes($data['message']) . ' - gabrielecirulli.com',
'headers' => 'From: "' . $data['name'] . '" <' . $data['email'] . '>'
);
// Send
if(mail(
$message['recipient'],
utf8_encode($message['subject']),
utf8_encode($message['body']),
$message['headers']
)) {
echo json_encode(array('status' => 'ok'));
} else {
exit_message('An unidentified error happened while sending your message.');
}
这是一个例子:如果我通过我的页面发送消息
http://www.gabrielecirulli.com/p/20120113-073417.png
如果我通过没有<meta charset="utf-8">的测试页面发送相同的消息:
http://www.gabrielecirulli.com/p/20120113-073503.png
结果如下:
http://www.gabrielecirulli.com/p/20120113-073737.png
正如您所见,没有元标记的页面实际上给出了正确的字符。
Google Chrome 和 Firefox 都会出现此问题。
【问题讨论】:
-
这完全是关于您的电子邮件发送机制,而不是关于您的表单。
-
不,不是。从没有元标记的页面发送消息会产生一个理智的电子邮件。添加元标记时,会出现这些符号。
-
您总是需要指定某些内容的编码。您需要设置元信息,告诉浏览器以哪种编码解释文本以及它应该以哪种编码将文本发送到服务器。电子邮件也是如此,您需要设置标头,告诉电子邮件客户端邮件的编码是什么。所以它是你如何准确地发送电子邮件!
-
我已经用一个例子更新了这个问题,请检查一下。
-
是的,我们得到问题。请向我们展示发送电子邮件的代码。