通过PHP中的表单类型html发送电子邮件

时间:2016-03-27 16:02:30

标签: php html email

<?php
//if "email" variable is filled out, send email
if (isset($_REQUEST['email']))  {

    //Email information
    $admin_email = "personalemail@gmail.com";
    $email = $_REQUEST['email'];
    $subject = $_REQUEST['subject'];
    $comment = $_REQUEST['comment'];

    //send email
    mail($admin_email, "$subject", $comment, "From:" . $email);

    //Email response
    echo "Thank you for contacting us!";
}
//if "email" variable is not filled out, display the form
else  {
?>

<form method="post">
    <input name="email" type="text" class="form-control" placeholder="Enter your email address...">
    <input name="subject" type="text" class="form-control" placeholder="Subject">
    <br>
    <textarea name="comment" class="form-control" rows="3"></textarea>
    <br>
    <div class="mesbutts">
        <button type="submit" class="btn btn-primary" value="Submit">Send</button>
        <button type="reset" value="Reset" class="btn btn-default" >Clear</button>
    </div>

</form>
<?php 
} 
?>

大家好,我似乎无法弄清楚如何让我的PHP代码通过使用表单发送电子邮件。我已经把我的个人电子邮件,我似乎无法收到它们。你能帮我看一下我语法中的错误吗?

谢谢你的伴侣!

1 个答案:

答案 0 :(得分:1)

我认为这对你很有帮助。但更好的方法是使用库通过php发送电子邮件,例如phpMailer,或者通过库。

   <?php
//if "email" variable is filled out, send email
if (isset($_REQUEST['email']))  {
    $headers  = 'MIME-Version: 1.0' . "\r\n"; // set mime version
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // set content-type as html
    //Email information
    $admin_email = "personalemail@gmail.com";
    $email = $_REQUEST['email'];
    $subject = $_REQUEST['subject'];
    $comment = $_REQUEST['comment'];

    //send email
    mail($admin_email, "$subject", $comment, "From:" . $email,$headers); // adding headers to mail

    //Email response
    echo "Thank you for contacting us!";
}
//if "email" variable is not filled out, display the form
else  {
?>

<form method="post">
    <input name="email" type="text" class="form-control" placeholder="Enter your email address...">
    <input name="subject" type="text" class="form-control" placeholder="Subject">
    <br>
    <textarea name="comment" class="form-control" rows="3"></textarea>
    <br>
    <div class="mesbutts">
        <button type="submit" class="btn btn-primary" value="Submit">Send</button>
        <button type="reset" value="Reset" class="btn btn-default" >Clear</button>
    </div>

</form>
<?php 
} 
?>