我正在学习php,我正在尝试使用html表单向自己发送电子邮件,但它不起作用。
<form action="index.php" role="form" method="post" name="emailform">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="comment">Text:</label>
<textarea type="textarea" class="form-control" id="textarea" rows="5" name="textarea"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit" name="submit">Submit</button>
</form>
<?php
function email()
{
$to = 'my_mail';
$message = $_POST['textarea'];
$from = $_POST['email'];
$subject = 'Portfolio';
$mail_headers = "From: " . $from . " <" . $from . ">\r\n";
$mail_headers .= "Reply-To: " . $from . "\r\n";
$mail_headers .= "X-Mailer: PHP/" . phpversion();
echo $to . " " . $message . " " . $from;
if(@mail($to, $subject, $message, $mail_headers))
echo @mail($to, $subject, $message, $mail_headers);
else echo "ERROR";
}
if(isset($_POST['submit']))
email();
?>
my_mail 是我的邮件(我在这里替换了它,但在代码中有我真实的电子邮件)。 代码似乎有用,实际上它显示 echo @mail ,但邮件没有出现在我的收件箱中
答案 0 :(得分:0)
代码看起来很好,但我认为因为@在邮件功能中你没有看到任何错误。如果您不想显示错误,可以像这样使用它:
<?php
if(@mail($to, $subject, $message, $mail_headers)){
echo "Mail Sent!";
}else{
print_r(error_get_last());
}
?>
这样就不会抛出错误,但你可以使用error_get_last()查看错误并记录下来。
PS您正在使用邮件功能2次,因此邮件将在其工作时发送两次。
答案 1 :(得分:0)
这是正确的方法。
<form action="contact.php" etc... etc..>
blah blah blah
</form>
然后创建一个新的php文件(contact.php)并使用以下
<?php
$field_name = $_POST["cname"];/* change " " according to your form */
$field_email = $_POST["cmail"];
$field_sub = $_POST["csub"];
$field_message = $_POST["cmsg"];
$to = "mailid1@mail.com, mailid2@mail.com";
$subject = " give subject" ;
$message = "message";
if(mail($to,$subject,$message))
{
echo "<script>alert('Your Message was sent Successfully. Thank You For Your Time !');</script>";
}
else
{
echo "<script>alert('Something wrong happened. Please try again later. Sorry For The Trouble'); </script>";
}
?>
<meta http-equiv="refresh" content="2; url=contact.html">
<!-- for coming back to intial page -->