PHP Contact form fail - php

I've written a php contact form and can't figure out why it is not sending an email. The form submits fine but doesn't send an actual email.
The below is my PHP code.
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!preg_match("/^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$/i", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'xyz#xyz.com';
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The HTML code below is the Contact form HTML:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="contactform">
<fieldset class="contact-fieldset">
<h2>Send us a message</h2>
<ul>
<li>
<label for="contactname">Your Name:</label>
<div class="ctinput-bg"><input type="text" name="contactname" id="contactname" value="" class="contact-input required" /></div>
</li>
<li>
<label for="email">Email:</label>
<div class="ctinput-bg"><input type="text" id="email" name="email" class="contact-input required email" /></div>
</li>
<li>
<label for="subject">Subject:</label>
<div class="ctinput-bg"><input type="text" name="subject" id="subject" class="contact-input required" /></div>
</li>
<li>
<label for="message">Your message:</label>
<div class="cttxtarea-bg"><textarea rows="6" cols="40" id="message" name="message" class="contact-textarea required"></textarea></div>
</li>
<li>
<div class="form-button contact-submit">
<span><input type="submit" value=" send message " name="submit" /></span>
</div>
</li>
</ul>
</fieldset>
</form>

On top of the solutions others have provided I would highly recommend using the SwiftMailer library.
I had to create an automated email feature and it was a nightmare to manually set up the headers and such. SwiftMailer saved me a heap of time, see here for an example.

Sounds like your mail function isn't set up properly. Check your php.ini file and ensure you have the correct SMTP server settings.
Also, unrelated to your original question, but I'm not sure that using <ul> to markup a form is semantically correct. A set of fields isn't really an unsorted list, I'd prefer to use a semantically-correct <table> or even a series of <div>s.

I see 2 things :
1- the declairation of $hasError = false in the top of your code (make shure it excist)
2 - Generate headers as this :
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
Hope this will do the trick,

You can try to check if the mail is actually send:
if (mail($to, $subject, $body)) {
echo("<p>Message successfully sent!</p>");
} else {
echo("<p>Message delivery failed...</p>");
}
And to be sure you can also do a var_dump of your headers to see if they are correct:
var_dump($headers);
These things won't solve the problem, but will surely help to debug it.

Related

sendmail.php not re-directing

I had/have the code below for users to send messages/emails from my website to my sites email address.
It was working fine, for weeks: Validating the field contents (if there was a blank 'required field', it asked for a "valid" field content i.e. email address), as long as there were no blank fields it was sending the email and was re-directing to the thank-you page - which acknowledges that the email has been sent.
Now, it has stopped working properly.
It doesn't seem to be validating (as it did originally) any more - as there are no warnings/errors for blank fields (if there is a blank field it simply doesn't send), it still sends the email to the address correctly (if there are no blank required fields), but it doesn't redirect to the thank-you page any more.
Here is the form code:
<form method="post" action="assets/sendmail.php">
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" placeholder="Enter your name...">
<label for="email" class="emailLabel">Email</label>
<input id="email" type="text" name="email" placeholder="Enter your email...">
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" placeholder="Your subject...">
<label for="message" class="messageLabel">Message</label>
<textarea id="message" name="message" placeholder="Your message..."></textarea>
<button type="submit">Send</button>
</form>
Here is the php code - note that I have substituted the email address for obvious reasons :)
<?php
// Email address verification
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$array = array();
$array['nameMessage'] = '';
$array['emailMessage'] = '';
$array['messageMessage'] = '';
if($clientName == '') {
$array['nameMessage'] = 'Please enter your name.';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Please insert a valid email address.';
}
if($message == '') {
$array['messageMessage'] = 'Please enter your message.';
}
if($clientName != '' && isEmail($clientEmail) && $message != '') {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
}
//echo json_encode($array);
{
header("location:../thankyou.html");
}
}
?>
Any help would be appreciated.
First of all, for email checking you can use built-in php as well.
filter_var($clientEmail, FILTER_VALIDATE_EMAIL)
I don't see where you output your errors so that may be why they are not showing,
I have added support for that
I have rewritten your code:
<?php
if (!empty($_POST)) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$errors = array();
if (empty($clientName)) {
$errors['nameMessage'] = 'Please enter your name.';
}
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
$errors['emailMessage'] = 'Please insert a valid email address.';
}
if (empty($message)) {
$errors['messageMessage'] = 'Please enter your message.';
}
// Are there errors?
if (count($errors) == 0) {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
header("location:../thankyou.html");
} else {
foreach ($errors as $err) {
echo $err . '<br />';
}
}
}
?>
Thank-you for the updated PHP code. Unfortunately, it hasn't made any difference. It still sends the email when all fields are filled in, it even sends if the "subject" is empty, but it still does not re-direct to the thank-you page. It doesn't send if Name, Email Address, and Message are empty. But it does not display errors. I have tried to place both files in the parent directory and removing the assets/ from the action in the form and the ../ in the PHP. as below
<form method="post" action="sendmail.php">
<label for="name" class="nameLabel">Name</label>
<input id="name" type="text" name="name" placeholder="Enter your name...">
<label for="email" class="emailLabel">Email</label>
<input id="email" type="text" name="email" placeholder="Enter your email...">
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" placeholder="Your subject...">
<label for="message" class="messageLabel">Message</label>
<textarea id="message" name="message" placeholder="Your message..."></textarea>
<button type="submit">Send</button>
</form>
And the PHP is as you supplied (changing the email address of course)
<?php
if (!empty($_POST)) {
// Enter the email where you want to receive the message
$emailTo = 'me#myemail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$errors = array();
if (empty($clientName)) {
$errors['nameMessage'] = 'Please enter your name.';
}
if (!filter_var($clientEmail, FILTER_VALIDATE_EMAIL)) {
$errors['emailMessage'] = 'Please insert a valid email address.';
}
if (empty($message)) {
$errors['messageMessage'] = 'Please enter your message.';
}
// Are there errors?
if (count($errors) == 0) {
// Send email
$headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject, $message, $headers);
header("location:thankyou.html");
} else {
foreach ($errors as $err) {
echo $err . '<br />';
}
}
}
?>
No Errors displayed if there are errors, no re-direct once sent. It just remains on the "contact" page and still displaying the completed form. Cannot understand why the re-direct was working but not now. Couldn't sign in when I posted this originally.

PHP Mail form does not send [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I copied the message form and PHP mail from a website. But it doesn't seem to work. It does not send anything or make any reaction. I tried to find the error, but I am not familiar with PHP. I tried editing the $emailFrom =... to $_POST['email']; but that doesn't work either..
HTML:
<div id="form-main">
<div id="form-div">
<form class="form" id="form1">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Naam"/>
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" placeholder="E-mail" />
</p>
<p class="text">
<textarea name="text" class="validate[required,length[6,300]] feedback-input" placeholder="Bericht"></textarea>
</p>
<div class="submit">
<input type="submit" value="Verstuur" id="button-blue"/>
<div class="ease"></div>
</div>
</form>
</div>
</div>
PHP:
<?php
include 'functions.php';
if (!empty($_POST)){
$data['success'] = true;
$_POST = multiDimensionalArrayMap('cleanEvilTags', $_POST);
$_POST = multiDimensionalArrayMap('cleanData', $_POST);
//your email adress
$emailTo ="lisa-ederveen#hotmail.com"; //"yourmail#yoursite.com";
//from email adress
$emailFrom =$_POST['email']; //"contact#yoursite.com";
//email subject
$emailSubject = "Mail from Porta";
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comment"];
if($name == "")
$data['success'] = false;
if (!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email))
$data['success'] = false;
if($comment == "")
$data['success'] = false;
if($data['success'] == true){
$message = "NAME: $name<br>
EMAIL: $email<br>
COMMENT: $comment";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8" . "\r\n";
$headers .= "From: <$emailFrom>" . "\r\n";
mail($emailTo, $emailSubject, $message, $headers);
$data['success'] = true;
echo json_encode($data);
}
}
?>
Your form was incomplete, it missed the method (POST) and action (your php filename)
Try this instead:
<div id="form-main">
<div id="form-div">
<form action="sendEmail.php" method="POST" class="form" id="form1">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Naam"/>
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" placeholder="E-mail" />
</p>
<p class="text">
<textarea name="comment" class="validate[required,length[6,300]] feedback-input" placeholder="Bericht"></textarea>
</p>
<div class="submit">
<input type="submit" value="Verstuur" id="button-blue"/>
<div class="ease"></div>
</div>
</form>
</div>
</div>
sendEmail.php
<?php
//include 'functions.php';
if (!empty($_POST)){
$data['success'] = true;
//$_POST = multiDimensionalArrayMap('cleanEvilTags', $_POST);
//$_POST = multiDimensionalArrayMap('cleanData', $_POST);
//your email adress
$emailTo ="lisa-ederveen#hotmail.com"; //"yourmail#yoursite.com";
//from email adress
$emailFrom =$_POST['email']; //"contact#yoursite.com";
//email subject
$emailSubject = "Mail from Porta";
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comment"];
if($name == "")
$data['success'] = false;
if (!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email))
$data['success'] = false;
if($comment == "")
$data['success'] = false;
if($data['success'] == true){
$message = "NAME: $name<br>
EMAIL: $email<br>
COMMENT: $comment";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8" . "\r\n";
$headers .= "From: <$emailFrom>" . "\r\n";
mail($emailTo, $emailSubject, $message, $headers);
$data['success'] = true;
echo json_encode($data);
}
}
?>
Firstly, your form: <form class="form" id="form1">
Forms default to GET if a method isn't specifically instructed.
Use POST like this if your HTML form and PHP are inside the same file:
<form class="form" id="form1" method="post">
since you are using POST arrays.
or
<form class="form" id="form1" method="post" action="your_handler.php">
if using a different file; I used your_handler.php as an example filename.
Also, <textarea name="text"...
that should be <textarea name="comment" as per your $_POST["comment"] array.
Using error reporting would have trigged an Undefined index text... notice.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
I have no idea what multiDimensionalArrayMap('cleanEvilTags' does, so you'll have to check that.
If you're still not receiving mail, check your Spam.
Doing:
if(mail($emailTo, $emailSubject, $message, $headers)){
echo "Mail sent.";
}
and if it echoes "Mail sent", then mail() would have done its job. Once it goes, it's out of your hands.
You could look into using PHPMailer or Swiftmailer which are better solutions, as is using SMTP mailing.
Now, if (!empty($_POST)){ that isn't a full solution. It is best using a conditional !empty() for all your inputs. Your submit counts as a POST array and should only be relied on using an additional isset() for it.
If you're using this from your own computer, make sure that you've a Webserver installed. We don't know how your script is being used.
If you are using it from your own machine, make sure that PHP is indeed running, properly installed and configured, including any mail-related settings.
Additional notes:
You should also use full and proper bracing for all your conditional statements.
This has none:
if($comment == "")
$data['success'] = false;
which should read as
if($comment == ""){
$data['success'] = false;
}
Same thing for:
if($name == "")
$data['success'] = false;
Not doing so, could have adverse effects.
"I copied the message form and PHP mail from a website."
Again, about multiDimensionalArrayMap('cleanEvilTags'; if you don't have that function, then you will need to get rid of it and use another filter method for your inputs.
Consult the following on PHP.net for various filter options:
http://php.net/manual/en/filter.filters.php
http://php.net/manual/en/function.filter-input.php
http://php.net/manual/en/function.filter-var.php

My PHP Contact Form is not working

I am creating a website and I was making a contact form with PHP. It is turning up no errors on the page itself but the email never shows up in the inbox or spam folder of my email. The code I have for it is:
$_NAME = $_POST["name"];
$_EMAIL = $_POST["reply"];
$_SUBJECT = $_POST["subject"];
$_MESSAGE = $_POST["message"];
$_MAILTO = "myemail#gmail.com";
$_SUBJECT = "Contact Form";
$_FORMCONTENT = "From: ".$_NAME." Subject: ".$_SUBJECT." Message: ".$_MESSAGE;
$_MAILHEADER = "Reply To: ".$_EMAIL;
mail($_MAILTO, $_SUBJECT, $_FORMCONTENT, $_MAILHEADER);
Any ideas what the problem is?
EDIT --
Here's the HTML form:
<form id="contact" name="contact" action="contact2.php" method="post">
<input type="text" class="name" name="name" id="name" placeholder="Your name (optional)" onfocus="placeholder=''" onblur="placeholder='Your name (optional)'" /><br><br>
<input type="text" class="reply" id="reply" name="reply" placeholder="Your email (optional)" onfocus="placeholder=''" onblur="placeholder='Your email (optional)'" /><br><br>
<input type="text" class="subject" id="subject" name="subject" placeholder="Subject" onfocus="placeholder=''" onblur="placeholder='Subject'" /><br><br>
<textarea class="message" id="message" name="message" rows="10" cols="50" placeholder="Enter your message" onfocus="placeholder=''" onblur="placeholder='Enter your message'"></textarea><br><br>
<input type="submit" class="send" id="send" name="send" value="Send Message" />
</form>
First step would be to check the return value of the mail function to see if the email was successfully (as far as PHP/mail function can ascertain) sent.
$mail_result = mail($_MAILTO, $_SUBJECT, $_FORMCONTENT, $_MAILHEADER);
if ($mail_result) {
echo <<<HTML
<div>Mail was successfully sent!</div>
HTML;
} else {
echo <<<HTML
<div>Sending mail failed!</div>
HTML;
}
Secondly, you should check that all appropriate settings are correctly set in your php.ini file, specifically the sendmail_path setting. You should definitely take a look at official documentation in the PHP Manual.
As a last ditch effort, you may want to look into an alternate method of sending the mail.
Simple Example:
<?php
// Has the form been submitted?
if (isset($_POST['send'])) {
// Set some variables
$required_fields = array('name', 'email'); // add fields as needed
$errors = array();
$success_message = "Congrats! Your message has been sent successfully!";
$sendmail_error_message = "Oops! Something has gone wrong, please try later.";
// Cool the form has been submitted! Let's loop
// through the required fields and check
// if they meet our condition(s)
foreach ($required_fields as $fieldName) {
// If the current field in the loop is NOT part of the form submission -OR-
// if the current field in the loop is empty
if (!isset($_POST[$fieldName]) || empty($_POST[$fieldName])) {
// add a reference to the errors array, indicating that these conditions have failed
$errors[$fieldName] = "The {$fieldName} is required!";
}
}
// Proceed if there aren't any errors
if (empty($errors)) {
// add fields as needed
$name = htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8' );
$email = htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8' );
// Email receivers
$to_emails = "anonymous1#example.com, anonymous2#example.com";
$subject = 'Contact form sent from ' . $name;
$message = "From: {$name}";
$message .= "Email: {$email}";
$headers = "From: {$name}\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
if (mail($to_emails, $subject, $message, $headers)) {
echo $success_message;
} else {
echo $sendmail_error_message;
}
} else {
foreach($errors as $invalid_field_msg) {
echo "<p>{$invalid_field_msg}</p>";
}
}
}

Script should send an email containing form submission values, but no email is getting sent

So I have a HTML form with some PHP but I'm not getting any email whatsoever after submitting it. I can't find the problem! can you help me out?
Tried changing the if(isset($_POST['submit'])) { to 'enviar' but still not working.
tried putting some echos to see where it's not working. the only statement that is stopping at the else statement is stripslashes.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Before getting any email, you have to be sure the email is being sent.
$sent = mail($emailTo, $subject, $body, $headers);
var_dump($sent);
What does this code output when placed in the appropriate place?
Have you tried a simple php page to do a test Email (eg fixed content) and I assume the webserver has email configured and is prepared to relay for your address?
If this is WordPress contact form, for starters:
mail($emailTo, $subject, $body, $headers);
should be:
wp_mail($emailTo, $subject, $body, $headers);
See: wp_mail codex
Now you have to check your e-mail setup, as well as WordPress e-mail setup too.

HTML/PHP form not sending email

I have a form which does everything right except send the input values to my email, what am I doing wrong? Ps: not using local server, so that's not it.
EDIT: I'm not getting any email whatsoever.
Tried changing the if(isset($_POST['enviar'])) { part but still not working.
Tried the chatty echos. the only if statement that isn't behaving properly is stripslashes. It stops at the else statement.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The ereg() family of functions are deprecated. use the preg_...() equivalents instead. They work almost exactly the same, except requiring delimiters around the match patterns.
As well, don't use PHP_SELF in your form. That value is raw user-supplied data and can be trivially subverted for an XSS attack.
Checking for a particular form field to see if a POST occured is somewhat unreliable - you might change the field's name later on and your check will fail. However, this
if ($_SERVER['REQUEST_METHOD'] == 'POST) { ... }
will always work, no matter how many or few fields are in the form, as long as the form was actually POSTed.
As for the actual problem, I'm assuming the mail is getting sent out, or you'd have complained about that. That means your variables aren't being populated properly. Instead of just sending the mail, echo out the various variables as they're built, something like:
echo 'Checking name';
if ($_POST['name'] .....) {
echo 'name is blank';
} else {
$name = ...;
echo "Found name=$name";
}
Basically have your code become extremely "chatty" and tell you what it's doing at each stage.
#dafz: Change
if(isset($_POST['submit'])) {
to
if(isset($_POST['enviar'])) {
#Marc B deserves another up-vote for his answer as well.
Edit
You can try the following update.
if(!isset($hasError)) {
$siteAddress = 'validaddress#yourdomain.com'; //Put admin# or info# your domain here
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \r\nEmail: $email \r\nSubject: $subject \r\nComments: $comments \r\n";
$headers = 'To: ' . $name . ' <' . $emailTo . '>' . "\r\n";
$headers .= 'From: My Site <' . $siteAddress . '>' . "\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";
if (mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
} else {
$emailSent = false;
}
}

Categories