PHP email form received from postmaster#domain.co.uk - php

I receive my email from postmaster#domain.co.uk instead of the $email I specified.
the php should set $email as the person sending the email but It goes to the default postmaster#domain.co.uk
<?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]));
}
mb_convert_encoding($string, "UTF-8"); //AUTO DETECT AND CONVERT
mb_convert_encoding($string, "UTF-8", "latin1");
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$telephone = $_POST["telephone"];
$pages = $_POST["pages"];
$budget = $_POST["budget"];
$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($telephone) < 6) {
if(!$telephone) {
$errors[] = "You must enter a phone number.";
} else {
$errors[] = "Message must be at least 6 characters. (include area code)";
}
}
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'>The following errors occured:<ul>". $errortext ."</ul></span>");
}
// Send the email
$to = "contact#dorsetdesigns.co.uk";
$subject = "Quote Request: $name";
$message = "Telephone Number: $telephone"."<br />"."Job Details: $message"."<br />"."Number of Pages Required: $pages"."<br />"."Clients Budget: $budget";
$headers = 'Content-Type: text/html; charset=utf-8';
"Quote Request From: $email";
mail($to, $subject, $message, $headers);
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</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;
}
?>
and the js
$(function() {
// Validate the contact form
$('#contactform').validate({
// Specify what the errors should look like
// when they are dynamically added to the form
errorElement: "label",
wrapper: "td",
errorPlacement: function(error, element) {
error.insertBefore( element.parent().parent() );
error.wrap("<tr class='error'></tr>");
$("<td></td>").insertBefore(error);
},
// Add requirements to each of the fields
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
telephone: {
required: true,
minlength: 6
},
message: {
required: true,
minlength: 10
}
},
// Specify what error messages to display
// when the user does something horrid
messages: {
name: {
required: "Please enter your name.",
minlength: jQuery.format("At least {0} characters required.")
},
email: {
required: "Please enter your email.",
email: "Please enter a valid email."
},
telephone: {
required: "Please enter a phone number.",
minlength: jQuery.format("At least {0} characters required.")
},
message: {
required: "Please enter a message.",
minlength: jQuery.format("At least {0} characters required.")
}
},
// Use Ajax to send everything to quote.php
submitHandler: function(form) {
$("#send").attr("value", "Sending...");
$(form).ajaxSubmit({
target: "#response",
success: function(responseText, statusText, xhr, $form) {
$(form).slideUp("fast");
$("#response").html(responseText).hide().slideDown("fast");
}
});
return false;
}
});
});

$headers = 'Content-Type: text/html; charset=utf-8';
"Quote Request From: $email";
Should be:
$headers = 'Content-Type: text/html;\ncharset=utf-8;\nFrom: $email';

Don't have the ability to check right now, but I don't think the From address is being added to your $header variable.
$headers = 'Content-Type: text/html; charset=utf-8';
"Quote Request From: $email";
Here is an example of setting up additional headers I found on the PHP Mail Manual.
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
http://www.php.net/manual/en/function.mail.php
Yours... at least according to the documentation.
$headers = 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= "From: $email" . "\r\n";

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"; }
}
}
?>

PHP Send Email Even If Validation Errors

I have the following code on one of my signup pages. I'm trying to figure out how to only generate the email if there are no errors...right now, it sends the email no matter what so I'm getting conflicting emails.
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
//Forms posted
if(!empty($_POST))
{
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$displayname = trim($_POST["displayname"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
$captcha = md5($_POST["captcha"]);
if ($captcha != $_SESSION['captcha'])
{
$errors[] = lang("CAPTCHA_FAIL");
}
if(minMaxRange(4,25,$username))
{
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT",array(4,25));
}
if(!ctype_alnum($username)){
$errors[] = lang("ACCOUNT_USER_INVALID_CHARACTERS");
}
if(minMaxRange(4,60,$displayname))
{
$errors[] = lang("ACCOUNT_DISPLAY_CHAR_LIMIT",array(4,60));
}
if(minMaxRange(4,50,$password) && minMaxRange(4,50,$confirm_pass))
{
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT",array(4,50));
}
else if($password != $confirm_pass)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if(!isValidEmail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
//End data validation
if(count($errors) == 0)
{
//Construct a user object
$user = new User($username,$displayname,$password,$email);
//Checking this flag tells us whether there were any errors such as possible data duplication occured
if(!$user->status)
{
if($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE",array($username));
if($user->displayname_taken) $errors[] = lang("ACCOUNT_DISPLAYNAME_IN_USE",array($displayname));
if($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE",array($email));
}
else
{
//Attempt to add the user to the database, carry out finishing tasks like emailing the user (if required)
if(!$user->userCakeAddUser())
{
if($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if(count($errors) == 0) {
$successes[] = $user->success;
}
}
echo resultBlock($errors,$successes);
$to = 'myemail#domain.com';
$subject = 'New User Signup';
$url = 'mydomain.com/account.php';
$headers .= "From: myemail#domain.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message .= '<html><body>';
$message .= "<p>...message contents...</p>";
mail($to, $subject, $message, $headers);
echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">';
?>
I'm sure it's because I start the email stuff in the wrong place, but when I try to move it elsewhere, I get various errors.
Thanks in advance for any help you can provide.
Wrap your mail code inside like this:
if(count($errors) == 0) {
$to = 'myemail#domain.com';
$subject = 'New User Signup';
$url = 'mydomain.com/account.php';
$headers .= "From: myemail#domain.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message .= '<html><body>';
$message .= "<p>...message contents...</p>";
mail($to, $subject, $message, $headers);
}
Both your if(count($errors) == 0) conditions are doing exactly the same thing. You don't need to add a new condition but remove one. Your script can be simplified like this (pseudocode):
// some processing
// ...
//Forms posted
if(!empty($_POST))
{
// filling $errors[]
//End data validation
if(count($errors) == 0)
{
//Construct a user object
// ...
//Checking this flag tells us whether there were any errors such as possible data duplication occured
// ...
$successes[] = $user->success;
// Send email if no error
// ...
mail($to, $subject, $message, $headers);
}
}
echo resultBlock($errors,$successes);
$url = 'mydomain.com/account.php';
echo '<META HTTP-EQUIV=Refresh CONTENT="1; URL='.$url.'">';

Php email script failed

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?

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.

Mail delivery failed: returning message to sender

I would like to add a failed message re-direct to my mail script, so that if a user enters a wrong address in the email field it gets returned to me, and not to my hosting company's inbox, how do I do that? I've already added return-path but doesn't work, what else can i do to get this code to work.
Here is the code:
<?php if(isset($_POST['submit'])) {
if(trim($_POST['first-name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['first-name']);
}
//Check to make sure that the last name field is not empty
if(trim($_POST['last-name']) == '') {
$hasError = true;
} else {
$lname = trim($_POST['last-name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if(!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure that the phone field is not empty
if(trim($_POST['tel']) == '') {
$hasError = true;
} else {
$phone = trim($_POST['tel']);
}
//Check to make sure that the phone field is not empty
if(trim($_POST['company']) == '') {
$hasError = true;
} else {
$company = trim($_POST['company']);
}
foreach (array($_POST['q1']) as $value) {
$q1 = $value[0];
$q2 = $value[1];
$q3 = $value[2];
}
//If there is no error, send the email
if(!isset($hasError)) {
$to = 'me#host.com';
$recipient = $email;
$subject = 'Subject';
$headers = "From: Me\n" . $to . "\r\n";
$headers .= "Reply-To: ". $to . "\r\n";
$headers .= "Return-Path: ". $to . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$msg1 = "First Message";
$msg2 = "Second Message";
//Send Email
mail($recipient, $subject, $msg2, $headers);
mail($to, $subject, $msg1, $headers);
$emailSent = true;
}
}
?>
the return path is set by the mta based on the envelope sender, you can't just set that in the headers yourself. You can try to set the envelope sender using the $additional_parameters argument of the mail function. See Example #3 on http://www.php.net/manual/en/function.mail.php
In your case, that would be something like
mail($recipient, $subject, $msg2, $headers, "-f $to");
On some systems overriding the envelope sender using -f is restricted. In that case you'd probably have to switch to submitting the mail via SMTP instead of calling the sendmail binary via mail().

Categories