contact form not sending senders email

风流意气都作罢 提交于 2020-01-17 02:19:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!