sendmail.php not re-directing - php

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.

Related

php email form redirects incorrectly after sending

I'm using a template for my website that I found online. It came with a contact form html page and a sendmail php file. The form works and I receive the email in my inbox, but, for some reason, after I hit the 'send' button, the browser redirects to a blank page with the following (error?) message:
" {"nameMessage":"","emailMessage":"","messageMessage":""} "
The only thing that I can think of that I've changed (in the php file) is the email address where the messages are sent.
I am wondering how I can avoid this message and redirect to another page (thanks.html) instead?
Specifically, what code do I need to add, remove or replace to fix this issue please?
Here is the HTML and PHP code:
HTML:
<div class="contact-us container">
<div class="row">
<div class="contact-form span7" html_id="contactfrm">
<p>Want to get in touch? Use the form below to send an email.</p>
<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 id="button">Send</button>
</form>
</div>
</div>
</div>
PHP:
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 = 'email#gmail.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);
}
?>
p.s. I've noticed that there have been previous posts regarding this issue but I'm quite a newbie (especially with PHP).
After you have written
echo json_encode($array);
write ,
header('Location:thanks.php');
this will redirect you to thanks.php page and there you can write your html/php code.

Add extra INPUT to contact form email PHP

I'm using some php i found for sending a contact form from my site.
The HTML looks like this:
<div id="wrap">
<div id='form_wrap'>
<form id="contact-form" action="javascript:alert('success!');">
<p id="formstatus"></p>
<input type="text" name="name" value="" id="name" placeholder="Voornaam" required/>
<input type="text" name="email" value="" id="email" placeholder="E-mail adres" required/>
<textarea name="message" value="Your Message" id="message" placeholder="Uw vraag of projectomschrijving" required></textarea>
<input type="submit" name ="submit" value="Offerte aanvragen" />
</form>
</div>
</div>
The PHP looks like this:
<?php
define("WEBMASTER_EMAIL", 'your#emailadress.com');
error_reporting (E_ALL ^ E_NOTICE);
function ValidateEmail($email)
{
$regex = '/([a-z0-9_.-]+)'. # name
'#'. # at
'([a-z0-9.-]+){2,255}'. # domain & possibly subdomains
'.'. # period
'([a-z]+){2,10}/i'; # domain extension
if($email == '')
return false;
else
$eregi = preg_replace($regex, '', $email);
return empty($eregi) ? true : false;
}
$post = (!empty($_POST)) ? true : false;
if($post)
{
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name || $name == "Name*")
$error .= 'Please enter your name.<br />';
// Check email
if(!$email || $email == "Email*")
$error .= 'Please enter an e-mail address.<br />';
if($email && !ValidateEmail($email))
$error .= 'Please enter a valid e-mail address.<br />';
// Check message
if(!$message)
$error .= "Please enter your message. <br />";
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
echo 'OK';
}
else
echo '<div class="formstatuserror">'.$error.'</div>';
}?>
It works great! BUT i need to add a few more INPUTS in my form. I know how to add those to the html. For instance I added this one:
<input type="text" name="lastname" value="" id="lastname" placeholder="Achternaam" required/>
But I just can't find the good way to add this input to the email that I receive in my mailbox... Where do I add this in the PHP? I tried lots of things...
Hope you guys can help me out!
David
After these lines:
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
You instanciate a variable containing the value for your field (lastname):
$lastname = stripslashes($_POST['lastname']);
Then you validate your input if it's empty or something else:
// Check message
if(!$lastname )
$error .= "Please enter your lastname. <br />";
And finally, you use your variable lastname to display it on the email message:
"From: ".$name." ".$lasname." <".$email.">\r\n"
Et voilĂ  !
EDIT: If you want to use this input on the message, you have the $message variable, and you can do so :
if(!$error)
{
$message .= "<p>Message sent by $lastname";
...
If you didn't want it going in the email headers as an addition to the 'From' or 'Subject', you could also keep appending information to the body of the email, or your $message. For example:
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = stripslashes($_POST['subject']);
$message = "Last Name: " . stripslashes($_POST['lastname']) . "\r\n";
$message .= "Message: " . stripslashes($_POST['message']);
The other options work as well, it really just depends 'where' in the email you want this extra information going.

PHP email contact form displays error

Every time I attempt to submit this contact form I receive the following error message:
'Please enter your message.'
The name error message and email error message do not appear unless I leave them blank. I attempted specifying post in the HTML.
Here is the HTML:
<div class="col-md-8 animated fadeInLeft notransition">
<h1 class="smalltitle">
<span>Get in Touch</span>
</h1>
<form action="contact.php" method="post" name="MYFORM" id="MYFORM">
<input name="name" size="30" type="text" id="name" class="col-md-6 leftradius" placeholder="Your Name">
<input name="email" size="30" type="text" id="email" class="col-md-6 rightradius" placeholder="E-mail Address">
<textarea id="message" name="message" class="col-md-12 allradius" placeholder="Message" rows="9"></textarea>
<img src="contact/refresh.jpg" width="25" alt="" id="refresh"/><img src="contact/get_captcha.php" alt="" id="captcha"/>
<br/><input name="code" type="text" id="code" placeholder="Enter Captcha" class="top10">
<br/>
<input value="Send" type="submit" id="Send" class="btn btn-default btn-md">
</form>
</div>
Here is the PHP:
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your message.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'faasdfsdfs#gmail.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($comment) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
In your HTML form you name your <input... field "message" but then when you are in PHP you try to get the value from `$_GET['comment'].
I think if you get those lined up I think it will solve your problem.
I can see 2 issues:
Receive $_GET['comment'] or $_POST['comment'] but next you're using $message var
Do not use if($_POST) because $_POST as a superglobal
is always setted.
I suggest use this for check if a POST have been sent
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {}
or this in case you want to check is not empty
if ( !empty($_POST) ) {}
How to detect if $_POST is set?

Confirmation Email will not send

So i have this contact form, everything sends fine after the submit button is pressed. However the confirmation email does not seem to send...
I couldnt find the answer on here anywhere, or i would not have asked
The Confirmation email code
<?php
$your_email = "jp.vaughan#icloud.com"; // email address to which the form data will be sent
$subject = "Contact Email";
$thanks_page = "/contact/thankyou.html";
if (isset($_POST["submit"])) {
$nam = $_POST["name"];
$ema = trim($_POST["email"]);
$org = trim($_POST["organisation"]);
$com = $_POST["comments"];
$loadtime = $_POST["loadtime"];
if (get_magic_quotes_gpc()) {
$nam = stripslashes($nam);
$ema = stripslashes($ema);
$org = stripslashes($org);
$com = stripslashes($com);
}
$error_msg=array();
if (empty($nam) || !preg_match("~^[a-z\-'\s]{1,60}$~i", $nam)) {
$error_msg[] = "The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}
if (empty($ema) || !filter_var($ema, FILTER_VALIDATE_EMAIL)) {
$error_msg[] = "Your email must have a valid format, such as name#mailhost.com";
}
if (empty($org) || !preg_match("~^[a-z\-'\s]{1,60}$~i", $org)) {
$error_msg[] = "The Organisation must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}
$limit = 1000000000000000000000000000000000000;
if (empty($com) || !preg_match("/^[0-9A-Za-z\/-\s'\(\)!\?\.,]+$/", $com) || (strlen($com) > $limit)) {
$error_msg[] = "Your message must contain only letters, digits, spaces and basic punctuation ( ' - , . )";
}
$totaltime = time() - $loadtime;
if($totaltime < 7) {
echo("<p>Please fill in the form before submitting!</p>");
echo '</ul>
<form method="post" action="', $_SERVER['PHP_SELF'], '">
<input placeholder="Your Name*" name="name" type="text" id="name" value="'; if (isset($_POST["name"])) {echo $nam;}; echo '">
<input placeholder="Your Email Address*" name="email" type="email" id="email"'; if (isset($_POST["email"])) {echo $ema;}; echo '">
<input placeholder="Your Organisation*" name="organisation" type="text" id="organisation" value="'; if (isset($_POST["organisation"])) {echo $org;}; echo '">
<textarea placeholder="Your Message" name="comments" rows="5" cols="50" id="comm">'; if (isset($_POST["comments"])) {echo $com;}; echo '</textarea>
<input type="hidden" name="loadtime" value="', time(), '">
<input type="submit" name="submit" value=" SEND" id="submit">
</form>';
exit;
}
if ($error_msg) {
echo '
<p>Unfortunately, your message could not be sent. The form as you filled it out is displayed below. Make sure each field is completed. Please address any issues listed below:</p>
<ul class="err">';
foreach ($error_msg as $err) {
echo '<li>'.$err.'</li>';
}
echo '</ul>
<form method="post" action="', $_SERVER['PHP_SELF'], '">
<input placeholder="Your Name*" name="name" type="text" id="name" value="'; if (isset($_POST["name"])) {echo $nam;}; echo '">
<input placeholder="Your Email Address*" name="email" type="email" id="email"'; if (isset($_POST["email"])) {echo $ema;}; echo '">
<input placeholder="Your Organisation*" name="organisation" type="text" id="organisation" value="'; if (isset($_POST["organisation"])) {echo $org;}; echo '">
<textarea placeholder="Your Message" name="comments" rows="5" cols="50" id="comm">'; if (isset($_POST["comments"])) {echo $com;}; echo '</textarea>
<input type="hidden" name="loadtime" value="', time(), '">
<input type="submit" name="submit" value=" SEND" id="submit">
</form>';
exit();
}
$email_body =
"Name of sender: $nam\n\n" .
"Email of sender: $ema\n\n" .
"Organisaition: $org\n\n" .
"COMMENTS:\n\n" .
"$com" ;
if (!$error_msg) {
mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>");
die ("Thank you. Your message has been sent to the appropriate person.");
exit();
}
$sendto = $_POST["email"]; // this is the email address collected form the form
$ccto = "jp.vaughan#icloud.com"; //you can cc it to yourself
$subjectCon = "Email Confirmation"; // Subject
$message = "the body of the email - this email is to confirm etc...";
$header = "From: auto-confirm#moibrahimfoundation.org\r\n";
// This is the function to send the email
if(isset($_POST['submit'])) {
mail($sendto, $subjectCon, $message, $header);
}}
?>
you are exiting the code after sending the first email.
if (!$error_msg) {
if (mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>");
die ("Thank you. Your message has been sent to the appropriate person."); //you are exiting here
exit(); //additional exit here. the second email won't be sent if there is no error.
}
$sendto = $_POST["email"]; // this is the email address collected form the form
$ccto = "jp.vaughan#icloud.com"; //you can cc it to yourself
$subjectCon = "Email Confirmation"; // Subject
$message = "the body of the email - this email is to confirm etc...";
$header = "From: auto-confirm#moibrahimfoundation.org\r\n";
// This is the function to send the email
if(isset($_POST['submit'])) {
mail($sendto, $subjectCon, $message, $header);
should be
$success='';
if (!$error_msg) {
if (mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>")){
$success="Thank you. Your message has been sent to the appropriate person.";
}else{
$success="Your message cannot be sent";
}
}
$sendto = $_POST["email"]; // this is the email address collected form the form
$ccto = "jp.vaughan#icloud.com"; //you can cc it to yourself
$subjectCon = "Email Confirmation"; // Subject
$message = "the body of the email - this email is to confirm etc...";
$header = "From: auto-confirm#moibrahimfoundation.org\r\n";
// This is the function to send the email
if(isset($_POST['submit'])) {
mail($sendto, $subjectCon, $message, $header);
die($success);
if your first mail is also not sending please check the mail configuration in your php.ini and verify that you can send mail through it.
use this tool for checking ur mail is sending or not...also it will show all parameters of mail function...
Test Tool

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