使用php和html表单发送电子邮件


Sending email with php and html form

我正在学习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,但邮件没有出现在我的收件箱

代码看起来不错,但我认为由于邮件函数中的@,您没有看到任何错误。如果你不想显示错误,你可以这样使用:

<?php
if(@mail($to, $subject, $message, $mail_headers)){
    echo "Mail Sent!";
}else{
    print_r(error_get_last());
}
?>

这样就不会抛出错误,但如果需要,可以使用error_get_last()查看错误并将其记录下来。

PS你使用了两次邮件功能,所以邮件在工作时会发送两次。

这里是正确的方法。

<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 -->