PHP contact form script not sending emails - php

I am not very good with php and my friend helped me with this php contact form script. But this does not seem to send emails to the desired address. Can you please suggest what might be the problem with this script?
I really appreciate it. Thanks
<?php
$error = array();
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') ) {
if(!empty($_POST['name'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your name.';
}
if(!empty($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
} else {
$error[] = 'Please enter a correct email address.';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['phone'])) {
if(filter_var($_POST['phone'], FILTER_VALIDATE_INT)) {
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
} else {
$error[] = '<i>Phone number</i> only expects number';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['time'])) {
$time = filter_var($_POST['time'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your best time to contact.';
}
if(!empty($_POST['msg'])) {
$msg = filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your message.';
}
if(empty($error)) {
$to = 'your#email.com';
$subject = 'from contact form';
$message = $phone . "\r\n";
$message .= $time . "\r\n";
$message .= $msg;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$name.' <'. $email.'>' . "\r\n" .
'Reply-To: '.$name.' <'. $email . '>' ."\r\n";
//echo '<pre>'; var_dump($to, $subject, $message, $headers); echo '</pre>'; die();
mail($to, $subject, $message, $headers);
}
}
?>
<?php
if(!empty($error)) {
echo '<ul class="error">';
echo '<li>' . implode('</li><li>', $error) . '</li>';
echo '</ul>';
}
?>
<form method="post" action="">
<input type="text" name="name" value="" placeholder="Enter your name" class="email_form"/>
<input type="text" name="email" value="" placeholder="Enter your email address" class="email_form"/>
<input type="text" name="phone" value="" placeholder="Phone number" class="email_form"/>
<input type="text" name="time" value="" placeholder="Best time to contact. e.g. 3 am" class="email_form"/>
<textarea name="msg" placeholder="Your message" class="email_form"></textarea>
<input type="image" value="submit" name="contact_submit" src="images/submit.png" width="96" height="43" class="email_button">
</form>

Change this line:
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') ) {
to
if(isset($_POST['contact_submit']) ) {
and
<input type="image" value="submit" name="contact_submit" src="images/submit.png" width="96" height="43" class="email_button">
to
<input type = "submit" value="submit" name="contact_submit">
PHP is looking for a submit type, and you're using an image type.
If you still want to use the image as the submit button:
You will need to change:
if(!empty($_POST['contact_submit']) && ($_POST['contact_submit'] == 'submit') )
to another conditional statement.
For example:
if(!empty($_POST['email'])){
You can always add on to that conditional statement with the other fields you wish to check if they are set/empty.
For example:
if(!empty($_POST['email']) || !empty($_POST['name'])){
Upon testing your code, the code did not work till those changes were made.
N.B.: If mail is still not being sent/received, you will need to make sure that mail() is indeed available for you to use, and/or check your logs and the Spam box.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
Which will trigger any errors found.
Footnotes:
The phone field needs to be all numbers, otherwise it will fail.
I.e.: 555-234-5678 did not work, but 5552345678 did, therefore you will need to inform your users of how it should be entered.
Edit: (full code) - copy exactly as shown while changing email#example.com to your own Email.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$error = array();
if(isset($_POST['contact_submit']) ) {
if(!empty($_POST['name'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your name.';
}
if(!empty($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
} else {
$error[] = 'Please enter a correct email address.';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['phone'])) {
if(filter_var($_POST['phone'], FILTER_VALIDATE_INT)) {
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
} else {
$error[] = '<i>Phone number</i> only expects number';
}
} else {
$error[] = 'Please enter your email address.';
}
if(!empty($_POST['time'])) {
$time = filter_var($_POST['time'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your best time to contact.';
}
if(!empty($_POST['msg'])) {
$msg = filter_var($_POST['msg'], FILTER_SANITIZE_STRING);
} else {
$error[] = 'Please enter your message.';
}
if(empty($error)) {
$to = 'email#example.com';
$subject = 'from contact form';
$message = $phone . "\r\n";
$message .= $time . "\r\n";
$message .= $msg;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$name.' <'. $email.'>' . "\r\n" .
'Reply-To: '.$name.' <'. $email . '>' ."\r\n";
//echo '<pre>'; var_dump($to, $subject, $message, $headers); echo '</pre>'; die();
mail($to, $subject, $message, $headers);
}
}
?>
<?php
if(!empty($error)) {
echo '<ul class="error">';
echo '<li>' . implode('</li><li>', $error) . '</li>';
echo '</ul>';
}
?>
<form method="post" action="">
<input type="text" name="name" value="" placeholder="Enter your name" class="email_form"/>
<input type="text" name="email" value="" placeholder="Enter your email address" class="email_form"/>
<input type="text" name="phone" value="" placeholder="Phone number" class="email_form"/>
<input type="text" name="time" value="" placeholder="Best time to contact. e.g. 3 am" class="email_form"/>
<textarea name="msg" placeholder="Your message" class="email_form"></textarea>
<input type = "submit" value="submit" name="contact_submit">
</form>
You can also show a message if it was sent successfully by replacing:
mail($to, $subject, $message, $headers);
with:
if(mail($to, $subject, $message, $headers)){
echo "Mail sent, thank you.";
}
else{
echo "There was an error.";
}
You can also log the error:
http://php.net/manual/en/function.error-log.php
0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
2 No longer an option.
3 message is appended to the file destination. A newline is not automatically added to the end of the message string.
4 message is sent directly to the SAPI logging handler.
I.e.:
if(mail($to, $subject, $message, $headers)){
echo "Mail sent, thank you.";
}
else{
error_log("Error!", 3, "/var/tmp/mail-errors.log");
}

Related

'phone' is not displayed in the mail form

The mail is sent successfully to my domain-mail. however, the 'phone' is not sent in the mail content.
The content of the mail comes like this.
You have been contacted by yourname with regards, their additional message
is as follows.
"What I want to say~~ "
You can contact yourname via email, omain#domain or via phone
What's the problem?
<form method="post" action="php/contact.php" name="contactform" id="contactform">
<input name="name" type="text" id="name" onClick="this.select()" value="Name" >
<input name="email" type="text" id="email" onClick="this.select()" value="E-mail" >
<input type="text" name="phone" id="phone" onClick="this.select()" value="Phone" />
<textarea name="comments" id="comments" onClick="this.select()" >Message</textarea>
<button type="submit" id="submit" data-top-bottom="transform: translateY(-50px);" data-bottom-top="transform: translateY(50px);"><span>Send Message </span></button>
</form>
<?php
require 'PHPMailer-master/PHPMailerAutoload.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = $_REQUEST['email'] ;
$fromName = $_REQUEST['name'] ;
$to_Email = "my#domain.com";
// Email address verification, do not edit.
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message"> Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have enter an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "my#domain.com";
$address = "my#domain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name with regards, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email or via phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
It seems to me that this needs to be corrected...
$e_reply =
<input type="text" name="phone" id="phone" onClick="this.select()" value="Phone" />
by removing "/" at the end of the tag may help you.

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.

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.

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