Mail delivery failed: returning message to sender - php

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().

Related

Why is my sended mail getting name in this formar?

Hi I have issue with using mail function in php.
I am getting email to my example#gmail.com but name of sender is something like : uid86787
Full email I will receive looks like this:
uid86787
Subject: Some subject
To: myEmail#gmail.com
---------------------------
Body of email
Name: exampleName (I entered in form)
Email: exampleEmail (I entered in form)
Message: exampleMessage (I entered in form)
From: myPage.eu
What I need is change name uid86787 to myPage.eu. How can I do that please?
<?php
$errors = array();
$errorMessage = '';
if (!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name)) {
$errors[] = 'Meno je prázdne';
}
if (strlen($name) < 3) {
$errors[] = 'invalid name';
}
if (empty($email)) {
$errors[] = 'Email is empty';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email is invalid';
}
if (empty($message)) {
$errors[] = 'Message is empty';
}
if (empty($errors)) {
$toEmail = 'example#gmail.com';
$emailSubject = 'Správa cez stránku page.example';
$headers = serialize(array('From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=iso-8859-1'));
$bodyParagraphs = array("Name: {$name}", "Email: {$email}", "Message:", $message, "From: mypage.eu}");
$body = join(PHP_EOL, $bodyParagraphs);
if (mail($toEmail, $emailSubject, $body, $headers)) {
$errorMessage = "<p style='color: green;'>{Email sended}</p>";
} else {
$errorMessage = 'Oops, something went wrong. Please try again later';
}
} else {
$allErrors = join('<br/>', $errors);
$errorMessage = "<p style='color: red;'>{$allErrors}</p>";
}
}
?>
Edit:
Why I have headers in serialize()
Answer: Live server runs on older php I think and it throws me error:
mail() function required 4th parameter as string
Before serialize I had it like this
$headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=iso-8859-1'];
Don't serialize() your headers. To make your headers a string, change
$headers = serialize(array('From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=iso-8859-1'));
to
$headers = "From: $email" . "\r\n" .
"Reply-To: $email" . "\r\n" .
'Content-type: text/html; charset=iso-8859-1';
See the examples on the PHP mail manual.
$headers = 'From: info#vrtaniestudni.eu';
This changed the name of sender.

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 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