使用php发送电子邮件错误

时间:2015-12-28 07:45:52

标签: php html email

所以有一个表单只能获取该人的电子邮件并将其发送到我指定的电子邮件地址。但我想我错误地编写了代码,因为我遇到了错误。我已经看到其他stackoverflow问题,但我不知道为什么这不起作用。 这是html中的表单。

<form style="margin-bottom:50px;" name="contactform" action="contact-form-handler.php" class="news-letter "method="post">
  <div class="subscribe-hide">
    <input type="text" name="email" class="form-control"  placeholder="Email Address"  >
    <button  type="submit"  class="btn"><i class="fa fa-envelope"></i></button>
  </div><!-- /.subscribe-hide -->
</form><!-- /.news-letter -->

这是不同文件中的PHP代码。

    <?php
$errors = '';
$myemail = 'masnadhossain@live.com';
   empty($_POST['email']))
{
    $errors .= "\n Error: all fields are required";
}

$email_address = $_POST['email'];

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";
$email_body = "You have received a new message. ".
" Here are the details:".
"Email: $email_address\n ";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}

?>

我得到的错误是服务器错误500

2 个答案:

答案 0 :(得分:1)

您的代码有语法错误请检查它。

第3行应该是:

if (empty($_POST['email']))
{
    $errors .= "\n Error: all fields are required";
}

答案 1 :(得分:0)

1。)您遇到的第一个问题是您是通过邮寄方式从表单输入发送电子邮件地址,但您没有使用它。

2。)To和From变量具有相同的电子邮件地址masnadhossain@live.com,这会产生冲突

3。)用于检查电子邮件地址有效性的Preg_Match是错误的。我在下面重写了你的代码。

如果您要从表单输入发布用户电子邮件(例如gmail,yahoomail等),此代码将帮助您。

如果您想在代码中初始化电子邮件,请更改

$email_address = strip_tags($_POST['email']);

可能是

$email_address = 'user1@gmail.com';

最后,From变量必须是指向您网站地址的电子邮件地址。在这种情况下,我认为它是masnadhossain@live.com

此代码正常运行。如果它能解决您的问题,请将其标记为正确答案....

<?php


//Users email address coming from form input eg. gmail,yahoomail etc.

$email_address = strip_tags($_POST['email']);

//validate the email address

$email_val= filter_var($email_address, FILTER_VALIDATE_EMAIL);
if (!$email_val){
echo "<font color=red><b>Invalid Email Address</b></font>";
exit();
}



$to=$email_val;
$subject = "Contact form submission";
$message = "Here is the message;

// set the from variable to any email pointing to your website

$from = "masnadhossain@live.com";
$headers = "From:" . $from;
$sent=mail($to,$subject,$message,$headers);
 if($sent)  {

print "<br><font color=green><b>Your mail was sent Successfully</b></font>";
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');

 } else  {
print "<br><font color=orange><b>We encountered an error sending your mail.</b></font>";

 }
?>