使用PHP发送html表单电子邮件

时间:2017-07-06 23:40:48

标签: php email

当我点击我的提交按钮时,它会提取我的form-to-email.php源代码。这是我第一次使用任何PHP。如何让它发送电子邮件?它可能只是链接不正确或格式不正确。

<form method="post" name="myemailform" action="form-to-email.php">
<div>
  <label for="name">Name:</label><br>
 <input type="text" id="name" name="user_name" size="45"><br>
</div>
<div>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="user_email" size="45"><br>
</div>
<div>
  <label for="message">Message:</label><br>
  <textarea type="text" id="message" name="user_message" size="600"></textarea><br>
</div>
<div>
  <input type = "submit" value = "Send Form">
  <input type = "reset" value = "reset">
</div>
</form>

这是我的PHP代码

<?php
if(isset($_POST['email'])) {

// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "codymaheu@yahoo.com";
$email_subject = "Testing";

function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.<br /><br />";
    echo $error."<br /><br />";
    echo "Please go back and fix these errors.<br /><br />";
    die();
}


// validation expected data exists
if(!isset($_POST['user_name']) ||
    !isset($_POST['user_email']) ||
    !isset($_POST['user_message'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');       
 }



$name = $_POST['user_name']; // required
$email_from = $_POST['user_email']; // required
$comments = $_POST['user_message']; // required


$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}

$string_exp = "/^[A-Za-z .'-]+$/";

if(!preg_match($string_exp,$name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
 }


if(strlen($comments) < 2) {
$error_message .= 'The Message you entered do not appear to be valid.<br />';
}

if(strlen($error_message) > 0) {
died($error_message);
}

$email_message = "Form details below.\n\n";


function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}



$email_message .= "First Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Message: ".clean_string($comments)."\n";

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

@mail($email_to, $email_subject, $email_message, $headers);  
?>

<!-- include your own success html here -->

Thank you for contacting us. We will be in touch with you very soon.

<?php

}
?>

1 个答案:

答案 0 :(得分:0)

像这样在按钮中添加名称,然后再试一次

<input type = "submit" value = "Send Form" name="email">