Php email script failed - php

I have some trouble with this, Anyone know why it won't work?
I have this homepage where it uses this script for sending an email, but it won't work.
When I call that I should get an email sent, but it just runs without any error.
<?php
$emailTo = 'youremail';
$siteTitle = 'SiteTitle';
//error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP
//If the form is submitted
if(isset($_POST['submitted'])) {
$hasError = false;
// require a name from user
if(trim($_POST['contactName']) === '') {
$nameError = 'name plz!';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
// need valid email
if(trim($_POST['email']) === '') {
$emailError = 'Forgot Email?';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'It's not right fool';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
// we need at least some content
if(trim($_POST['comments']) === '') {
$commentError = 'Forgot something=';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
// upon no failure errors let's email now!
if(!isset($hasError)) {
$subject = 'New message to '.$siteTitle.' from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $comments";
$headers = 'From: ' .' <'.$email.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
//Autoresponse
$respondSubject = 'Thank you for contacting '.$siteTitle;
$respondBody = "Your message to $siteTitle has been delivered! \n\nWe will answer back as soon as possible.";
$respondHeaders = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $emailTo;
mail($email, $respondSubject, $respondBody, $respondHeaders);
// set our boolean completion value to TRUE
$emailSent = true;
}
}
?>

Add \ in ', in all occurences
$emailError = 'It\'s not right fool';
instead of
$emailError = 'It's not right fool';

You need to escape any 's with \ in strings that are enclosed in 's. For example, you need to change $emailError = 'It's not right fool' to $emailError = 'It\'s not right fool'.
The same goes for "s when enclosed in "s.

You said it runs without any error, so it may not be a PHP error. Have you made sure that SMTP is set up properly on your sever? With the new code you just posted, are there any new errors?

Related

PHP send mail script not working with PHP version Version 5.3.10-1ubuntu3.15

The sendmail script I have below works on PHP version 5.6.14, but i've had to use the same script on a server that has version 5.3.10 and it just won't send. Do i need to change the syntax of my code to work with older PHP? if so what do i need to change?
<?php
$error = ""; // Initialize error as blank
$errorMsg = ""; // Initialize error as blank
if (isset($_POST['submit'])) { // check if the form is submitted
#### removing extra white spaces & escaping harmful characters ####
$name = trim($_POST['name']);
$email = $_POST['email'];
$phone = $_POST['telephone'];
$company = $_POST['company'];
$message = $_POST['message'];
#### start validating input data ####
#####################################
# Validate First Name #
// if its not alpha numeric, throw error
if (!ctype_alpha(str_replace(array("'", "-"), "",$name))) {
$error .= '<p class="error">Name should be alpha characters only.</p>';
}
// if first_name is not 2-50 characters long, throw error
if (strlen($name) < 2 OR strlen($name) > 50) {
$error .= '<p class="error">Name should be within 2-50 characters long.</p>';
}
# Validate Email #
// if email is invalid, throw error
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // you can also use regex to do same
$error .= '<p class="error">Enter a valid email address.</p>';
}
# Validate Phone #
// if phone is invalid, throw error
if ($phone == "") {
} elseif ($phone != "") {
if (!ctype_digit($phone) OR strlen($phone) != 10) {
$error .= '<p class="error">Enter a valid phone number.</p>';
}
}
# Validate Dealer select #
// if select dealer is empty, throw error
if(empty($messgae))
{
$error .= '<p class="error">Select a subject.</p>';
//$error=true;
}
#### end validating input data ####
#####################################
}
if($name === "" || $email === "" || $subject === ""){
$errorMsg = "Please go back and make sure you have filled out the form correctly";
} else {
if(isset($_POST["name"])) {
// Build the message body
$body .= "Name: ".$_POST["name"]."\n";
$body .= "Email: ".$_POST["email"]."\n";
$body .= "Phone: ".$_POST["telephone"]."\n";
$body .= "Company: ".$_POST["company"]."\n";
$body .= "Subject: ".$_POST["subject"]."\n";
if (isset($_POST['contact'][0])) {
$body .= "Can be contacted by email."."\n";
}
if (isset($_POST['contact'][1])) {
$body .= $_POST["subject"];
}
$body = wordwrap($body, 70);
$subject = $_POST["subject"];
$addr_from = "info#tandsadvertising.co.uk";
require_once('config.php');
/*define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'config.php'); */
$sendmail = mail($addr_to, $subject, $body, "From:" . $addr_from . "\n", "-f" . $addr_from );
if($sendmail) header("Location: /form/thankyou.php");
else { echo "send mail failed, please check settings"; }
}
}
?>

E-mail is not receiving after click onn submit [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
I have a contact form. Form action access this code after click on submit.
<?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 = 'xxxxxx#gmail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$message = trim($_POST['message']);
$subject = "New message from your site";
$array = array('nameMessage' => '', 'emailMessage' => '', '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);
}
?>
<?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 = 'xxxxxxxx#gmail.com';
$clientName = trim($_POST['name']);
$clientEmail = trim($_POST['email']);
$message = trim($_POST['message']);
$subject = "New message from your site";
$array = array('nameMessage' => '', 'emailMessage' => '', '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);
}
?>
But email is not coming from that form. Please tell me what i have to do. PHP curl is active. this code is runing on ubuntu based server...
If you use a localhost no email will be sent because localhost is a virtual server. Others, I don't know.

PHP Redirect Issue

I'm having a difficult time getting my page to redirect after form submission. I've followed the advice that I've been able to find so far and no luck. Any help would be greatly appreciated.
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
$subject = "CONTACT FORM";
//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 sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'email#domain.com';
$body = "Name: $name \nEmail: $email";
$headers = 'From: Bond Limo (Newsletter Signup) <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) {
header("Location: http://www.website.com");
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="side-form">
Your header is not being processed. In order for your header to be processed and the redirect to occur, you will have to call the die() function after your header. Like so:
<?php
if(isset($emailSent) && $emailSent) {
header("Location: http://www.website.com");
die();
}
?>
Additionally, your code can be optimized by not checking:<?php if(isset($hasError)) { //If errors are found ?> again. Rather, just connect it with the above if statement and use an else statement like so:
// If there is no error, send the email
if (!isset($hasError)) {
$emailTo = 'email#domain.com';
$body = "Name: $name \nEmail: $email";
$headers = 'From: Bond Limo (Newsletter Signup) <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
$emailSent = mail($emailTo, $subject, $body, $headers);
} else {
// Errors found
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
}

Contact form not sending email to my address

I am having trouble with my contact form, the message isn't being sent to the email address I specified. Could anyone tell me if I'm doing something wrong here:
$emailTo = 'email#myemailwenthere.com';
$siteTitle = 'My sitename went here';
error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP
//If the form is submitted
if(isset($_POST['submitted'])) {
// require a name from user
if(trim($_POST['contactName']) === '') {
$nameError = 'Forgot your name!';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
// need valid email
if(trim($_POST['email']) === '') {
$emailError = 'Forgot to enter in your e-mail address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
// we need at least some content
if(trim($_POST['comments']) === '') {
$commentError = 'You forgot to enter a message!';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
$subject = 'New message to ';
$sendCopy = "";
$body = "Name";
$headers = 'From: ' .' <'.$email.'>';
mail($emailTo, $subject, $body, $headers);
// upon no failure errors let's email now!
if(!isset($hasError)) {
$subject = 'New message to '.$siteTitle.' from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $comments";
$headers = 'From: ' .' <'.$email.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
//Autorespond
$respondSubject = 'Thank you for contacting '.$siteTitle;
$respondBody = "Your message to $siteTitle has been delivered! \n\nWe will answer back as soon as possible.";
$respondHeaders = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $emailTo;
mail($email, $respondSubject, $respondBody, $respondHeaders);
// set our boolean completion value to TRUE
$emailSent = true;
}
Try with a mini script to check or sending mail is possible:
<?php
$to = "somebody#example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster#example.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$txt,$headers);
?>
I would advise you to try PHPMailer with SMTP configured, it gives lot of flexibility.
PHPMailer

Contact form emails do not arrive at destination

I have a simple website with a php contact form set up.
The original contact form included:
$to = "my_email#gmail.com";
$subject = "New message: $name";
$message = "$message";
$headers = "From: $email";
mail($to, $subject, $message, $headers);
but, it never actually sent an emial. My hosting provider claimed they cannot allow such a thing since the way it is, email spoofing can be done. Fine. So, after reading a thread here (php Contact Form on website and reply-to email) I modified the part above to the following:
$to = "my_email#gmail.com";
$subject = "New message: $name";
$message = "$message";
$headers = "From: my_email#gmail.com" . "\r\n" .
"Reply-To: $email" . "\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($to, $subject, $message, $headers);
which worked fine.
Now, I pretty much just uploaded the same site (some design and textual changes, nothing big) under a new domain on the same host (even the same shared hosting server), but it doesn't work. The contact form confirms sending but emails do not arrive.
Any ideas?
Your help would be greatly appreciated :)
Update: for what it's worth, here's the full php file:
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
if(!$name) {
$errors[] = "You must enter a name.";
} else {
$errors[] = "Name must be at least 2 characters.";
}
}
if(!$email) {
$errors[] = "You must enter an email.";
} else if(!validEmail($email)) {
$errors[] = "You must enter a valid email.";
}
if(strlen($message) < 10) {
if(!$message) {
$errors[] = "You must enter a message.";
} else {
$errors[] = "Message must be at least 10 characters.";
}
}
if($errors) {
// Output errors and die with a failure message
$errortext = "";
foreach($errors as $error) {
$errortext .= "<li>".$error."</li>";
}
die("<span class='failure'><h3>Sorry, The following errors occured:</h3><ol>". $errortext ."</ol><a href='contact.html' class='more'>Refresh Form</a></span>");
}
// --------------------------------------//
// Send the email // INSERT YOUR EMAIL HERE
$to = "myemail#my_domain.com";
// --------------------------------------//
$subject = "Contact Form: $name";
$message = "$message";
$headers = 'From: myemail#my_domain.com' . "\r\n" .
'Reply-To: $email' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
// Die with a success message
die("<span class='success'><h3>Successfully Sent!</h3> Your message is on its way, we will respond to you shortly.</span>");
// A function that checks to see if
// an email is valid
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
?>
I take it you are setting $email, $message etc from the $_POST or $_GET variables from your form,
e.g
$email = $_POST['email'];
This may still not work if your hosting provider has disabled the php mail() from sending emails within php.ini
Have you looked into the php pear mail function?
It may be worth simply asking your hosting provider for an example of what is allowed. It shouldn't take them more than 5 minutes to write out a sample.

Categories