简体   繁体   中英

Can't seem to get my PHP form to send as though from user's email

I have tried everything but I can't seem to add the function to make it so that the email appears in my inbox as though from the user's email rather than my host name.

I've tried adding the header attributes but it still didn't seem to work.

Here's the code:

<?php
/* Set e-mail recipient */
$myemail = "julia@hotmail.com";

/* Check all form inputs using check_input function */

$email = check_input($_POST['email']);


/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "
The email below would like to be added to the mailing list.

E-mail: $email

";


// create email headers
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  


/* Send the message using mail() function */
mail($myemail, $subject, $message);

/* Redirect visitor to the thank you page */
header('Location: trial2.html');
exit();


/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>

</body>
</html>
<?php
exit();
}
?>

Thanks!

Take the $headers from here:

@mail($email_to, $email_subject, $email_message, $headers);  

and put it in here:

/* Send the message using mail() function */
mail($myemail, $subject, $message);

Then remove the first line (copied from a site somewhere I'd guess)

You should be left with

// create email headers
$headers = 'From: '.$email."\r\n".
  'Reply-To: '.$email."\r\n" .
  'X-Mailer: PHP/' . phpversion();

/* Send the message using mail() function */
mail($myemail, $subject, $message, $headers);

Note: your regex validating the email address will fail on addresses like myname@example.co.uk or myname@email.example.com . use PHP's filter_var instead.

2nd note: even if you get this to work your ISP may well block any mail that doesn't appear to originate from an email account on their servers, so the mail won't be delivered anyway. Better to set up a dummy account like webform@mydomain.com (use your actual domain), use that as a from address and include the user email in the body of the message.

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