HTML / PHP从表单

时间:2017-03-28 15:37:16

标签: php html sendmessage

我已经在这方面工作了一段时间,我对php很新。我发送这个邮件时遇到了麻烦。第二组关注此代码最有帮助:

<?php
    if(isset($_POST['submit'])){
        $to = "myEmail"; // this is your Email address
        $from = $_POST['emailAddress']; // this is the sender's Email address
        $fullName = $_POST['fullName'];
        $subject = "Form submission";
        $message = $fullName . " wrote the following:" . "\n\n" . $_POST['comment'];
        $message2 = "Here is a copy of your message " . $fullName . "\n\n" . $_POST['comment'];

        $headers = "From:" . $from;
        $headers2 = "From:" . $to;
        mail($to,$subject,$message,$headers);
        mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
        echo "Mail Sent. Thank you " . $fullName . ", we will contact you shortly.";
        // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>


<form method="post" action="contact.php">
    <div class="form-group">

        <label for="fullName">Name</label>
        <input type="text" class="form-control" id="fullName" name="fullName" placeholder="Jane Doe">

        <label for="emailAddress">Email</label>
        <input type="email" class="form-control" id="emailAddress" name="emailAddress" placeholder="jane.doe@example.com">

        <label for="comment">Comment</label>
        <textarea class="form-control" rows="3" name="comment" placeholder="Comment"></textarea>

        <button name="submit" type="submit" class="btn">Submit</button>

    </div>
</form>

非常感谢!

2 个答案:

答案 0 :(得分:1)

我建议使用PHPMailer。它是GitHub上的一个开源项目:PHPMailer - GitHub

此类允许您利用最着名的邮件平台的SMTP服务来获得使用PHP发送邮件的快速系统。
从HTML表单开始,使用此类设置代码非常简单:

<!DOCTYPE html>
<html>
<body>
<form method="post">
<input type="email" name="from" placeholder="From">
<input type="email" name="to" placeholder="To">
<input type="text" name="subject" placeholder="Subject">
<textearea name="content"></textarea>
</form>
</body>
</html>

<?php
require_once('PHPMailer_5.2.4\class.phpmailer.php');

if(isset($_POST["submit"])){
$username = 'YOUR_GMAIL_ACCOUNT';
$password = 'YOUR_ACCOUNT_PASSWORD';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
//$mail->addAttachment($_FILES["image"]["name"]); 
$mail->IsHTML(true);
$mail->Username = $username;
$mail->Password = $password;
$mail->SetFrom($_POST["from"]);
$mail->Subject = $_POST["subject"];
$mail->Body = $_POST["content"];
$mail->AddAddress($to);

if(!$mail->Send())
{
    echo "Mailer error : " . $mail->ErrorInfo . "<br>";
}
}
?>

正如您在PHP代码中所看到的,我使用Gmail SMTP服务发送此邮件。请注意,如果要使用其他服务,则必须更改SMTP服务器。
此外,您需要登录电子邮件服务才能访问SMTP服务,并且您需要经常启用通过第三方应用程序访问您的邮件帐户 在某些情况下,SMTP服务器不接受TLS或SSL加密。


是否可以在enctype="multipart/data"标记中添加附加form属性的附件,并通过$_FILES数组获取上传的文件。
我希望这会对你有所帮助!

答案 1 :(得分:0)

在您的代码中,第二个邮件功能的参数未完成,您没有定义subject2的值我认为您的第一条消息以正确的方式发送但第二条消息不会