Reputation: 3589
I've been trying to create a simple contact form using PHP. So, I've managed to get the form to work by plugging in values for all variables like so and it sends the email just fine:
$to = "[email protected]";
$subject = "Job";
$message = "Test";
$from = "[email protected]";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
However, as soon as I replace the values with $_REQUEST[var], the email gets sent to my Junk email with no from address:
$to = "[email protected]";
$subject = "Job";
$message = $_REQUEST['clientMessage'];
$from = $_REQUEST['clientEmail'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: $from";
mail($to,$subject,$message,$headers);
Screenshot of the email:
I'm getting the values through an ajax form using jQuery:
var clientName = $("#name").val();
window.alert(clientName);
var clientEmail = $("#email").val();
window.alert(clientEmail);
var clientMessage = $("#message").val();
window.alert(clientMessage);
var data = "from=" + clientEmail + "&subject=" + clientName + "&message=" + clientMessage;
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function() {
$("#loading").fadeOut(100).hide();
$("#name").val(' ');
$("#email").val(' ');
$("#message").val(' ');
$("#message-sent").fadeIn(100).show();
}
});
I've printed out clientName
, clientMessage
, and clientEmail
all right before sending them into the ajax form and they all print out with correct values. Any idea what I'm doing wrong?
HTML form:
<form id="contactMe" data-abide>
<input type="text" id="name">
<input type="text" id="email">
<textarea id="message"></textarea>
<button type="submit" id="sendEmail" class="button">Submit</button>
Upvotes: 1
Views: 222
Reputation: 74217
This is only a "supplement" to the accepted answer (good catch Nick), since the Email was treated as Junk/Spam.
Adding proper headers such as:
$headers = "From: $from";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
will help reduce the chance of E-mail ending up in Junk or treated as Spam.
Certain web sites will mark it as Spam if proper headers are not included.
More information on the mail()
can be found on PHP.net
Upvotes: 1
Reputation: 3692
You're using the wrong variable to read the client email. In your JS, you're pulling it into a variable called clientEmail
, but then you're giving it the name from
when passing the AJAX request:
var data = "from=" + clientEmail + "&subject=" + clientName + "&message=" + clientMessage;
So from within PHP, you should be accessing it as $_REQUEST['from']
, not $_REQUEST['clientEmail']
.
Upvotes: 3