1

因此,使用下面的 PHP 代码,我尝试发送电子邮件。出于某种原因,当我单击我的 html 联系页面上的提交按钮时,php 得到两个错误,

Error: all fields are required Error: Invalid email address

我知道它是一封正确的电子邮件,并且所有字段都已填写,我 99% 确定所有输入字段都是 HTML 文件中的正确名称.. 这是 PHP 代码

<?php 
$errors = '';
$myemail = 'support@Blocked for security.host22.com';//<-----Put Your email address here.
if(empty($_POST['name'])  || 
   empty($_POST['email']) || 
   empty($_POST['message']))
{
    $errors .= "\n Error: all fields are required";
}

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['message']; 

if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", 
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
    $to = $myemail; 
    $email_subject = "Contact form submission: $name";
    $email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message"; 

    $headers = "From: $myemail\n"; 
    $headers .= "Reply-To: $email_address";

    mail($to,$email_subject,$email_body,$headers);
} 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>
<head>
    <title>Contact form handler</title>
</head>

<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>


</body>
</html>

表单的 HTML:

            <form action="contact-form-handler.php" method="POST" enctype="text/plain" name="contactform">
            <label for='name'>Name:</label><br/><input type="text" name="name"><br/>
            <label for='email'>Email:</label><br/><input type="text" name="email"><br/>
            <label for='message'>Message:</label><br/><textarea name="message" cols=48 rows=4></textarea><br/>
            <input type="submit" name="submit" value="Send">
        </form>
4

2 回答 2

1

您的表格中的问题在这里:

enctype="text/plain"

$_POST对于 PHP 来说,将变量放入enctype应该要么被删除要么等于要么application/x-www-form-urlencoded要么multipart/form-data

于 2012-10-19T02:03:52.323 回答
0

所以电子邮件地址!preg_match。我个人不会费心尝试使用正则表达式来验证人们是否输入了真实的电子邮件地址,您最终会得到来自 SMTP 本身的验证。

至少现在只需删除这部分代码:

if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", 
$email_address))
{
$errors .= "\n Error: Invalid email address";
}

然后重新运行你的脚本,你就会知道正则表达式是问题所在。希望您以人们真正希望收到您发送的电子邮件的方式使用此脚本。如果是这种情况,我会让任何人烦恼的最多可能是通过在表单中​​输入两次来验证电子邮件地址?

于 2012-10-19T01:52:01.460 回答