我写了一个 php 联系表格,但不知道为什么它不发送电子邮件。表单提交正常,但未发送实际电子邮件。
下面是我的 PHP 代码。
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/i", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'xyz@xyz.com';
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
下面的 HTML 代码是联系表单 HTML:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="contactform">
<fieldset class="contact-fieldset">
<h2>Send us a message</h2>
<ul>
<li>
<label for="contactname">Your Name:</label>
<div class="ctinput-bg"><input type="text" name="contactname" id="contactname" value="" class="contact-input required" /></div>
</li>
<li>
<label for="email">Email:</label>
<div class="ctinput-bg"><input type="text" id="email" name="email" class="contact-input required email" /></div>
</li>
<li>
<label for="subject">Subject:</label>
<div class="ctinput-bg"><input type="text" name="subject" id="subject" class="contact-input required" /></div>
</li>
<li>
<label for="message">Your message:</label>
<div class="cttxtarea-bg"><textarea rows="6" cols="40" id="message" name="message" class="contact-textarea required"></textarea></div>
</li>
<li>
<div class="form-button contact-submit">
<span><input type="submit" value=" send message " name="submit" /></span>
</div>
</li>
</ul>
</fieldset>
</form>