简体   繁体   中英

PHP mail not showing senders email in from header frfom HTML form

Please could someone assist me in showing the senders email in the from header on the email. Please see code below, currently when i receive the email it shows the to email address in the from and the to.

HTML:

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

PHP:

<?php 
if(isset($_POST['submit'])){
    $to = "bestwayhomemaintenance@gmail.com"; 
    $from = $_POST['email']; 
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    //$headers = "From:" . $from;
    $headers = "From: $to \r\n";
    $headers .= "Reply-To: $from \r\n";
    //$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 " . $first_name . ", we will contact you shortly.";
    
    }
?>

You can't send from a gmail address unless you're sending through gmail's servers, which essentially means you can't use PHP's mail() function to do it. You may be able to try, but your messages will be marked as forgeries.

To set the envelope sender with the mail function, you need to use a -f parameter in the $additional_params parameter in the mail function.

Your script is vulnerable to header injection attacks, and it is also exploitable for cross-site scripting.

To avoid the forgery issue, I recommend sending directly through gmail, which mean you need to use SMTP, and the easiest way to do that is to use PHPMailer that you tagged this question with. Base your code on the examples provided with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM