问题
i don't know if this is a common problem but i can't seem to understand why it is happening. I am trying to process a form and have it send the details to an email. Simple enough. Here is the PHP code for it. When someone fills the form up it shows everything except the senders email. It comes out as unknown sender. Does anyone know how i can fix it? Thanks a lot to anyone who takes time out to look at this.
<?php
if($_POST["submit"]) {
$recipient="emailx@gmail.com";
$subject="Form to email message";
$Name=$_POST["Name"];
$Phone=$_POST["Phone"];
$senderEmail=$_POST["senderEmail"];
$comments=$_POST["comments"];
$mailBody="Name: $Name\nPhone: $Phone\nEmail: $senderEmail\n\n$comments";
mail($recipient, $subject, $mailBody, "From: $Name <$comments>");
$thankYou="<p>Thank you! Your message has been sent.</p>";
}
?>
回答1:
chris85 answered the question in the comments:
The
From
is$comments
shouldn't it be$senderEmail
?
However, it's not quite that simple. You can't just pick any from
email address and expect it to work. The email client will most likely spam your emails if you try to spoof the from address.
Whenever you change the From
header you also need to change the reply-to
header, in your case, You should probably put the From
header as one of the email addresses on your server and only change the reply-to
header to whatever the user in-putted. That way your messages are more likely to not be spammed because it doesn't look like you're trying to be sneaky.
Another option is to use a simple library to take care of all this for you.
Here's a real simple one I wrote: http://geneticcoder.blogspot.com/2014/08/wrapper-for-phps-mail-function.html
回答2:
It seems that the header is not set correctly. Try something like this:
<?php
if($_POST["submit"]) {
$recipient="emailx@gmail.com";
$subject="Form to email message";
$Name=$_POST["Name"];
$Phone=$_POST["Phone"];
$senderEmail=$_POST["senderEmail"];
$comments=$_POST["comments"];
$header = "From: $senderEmail" . "\r\n" .
"Reply-To: $senderEmail" . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$mailBody="Name: $Name\nPhone: $Phone\nEmail: $senderEmail\n\n$comments";
mail($recipient, $subject, $mailBody, $header);
$thankYou="<p>Thank you! Your message has been sent.</p>";
}
?>
The function reference for the php mail
function can be found here.
来源:https://stackoverflow.com/questions/30018724/contact-form-not-sending-senders-email