Solved

php mail fails on subsequent mail sending

Posted on 2012-12-23
15
372 Views
Last Modified: 2012-12-25
I have used following codes for sending mail to user and admin.
First code is for users and it works ok.
Only problem is it sometime lands on junk/spam.
However when it sends mail to admin after sending mail to user - there is no error notified.
But admin is not recieving mail.
I have checked message body is properly populated.
Email provided is valid and working.
Can someone please tell me where i am wrong and what measure i have to take to prevent user mail going to junk.
Thanks
$email_from = 'webadminmailid@hotmail.com';
            $email_message ='
            <html>
            <body>
             message body here
            </body>
            </html>
           
            


			$headers  = "MIME-Version: 1.0" .  "\r\n";
                    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";	
			$headers .= ' From: '.'mymailid@hotmail.com'."\r\n" .
                           'Reply-To: '.$email_from.'\r\n' .
                           'X-Mailer: PHP/' . 'phpversion()';
			@mail($email,'Thank-you', $email_message, $headers);

			
			
			

			$headers1 = '';
			$emailto  = "adminmailid@gmail.com";
	        $email_from1 = $_POST['email'];
	        $email_message1 = "A new user having following details has registered on ".date("Y-m-d")." at ".date("H:i")."\n\n";
	        foreach($_POST as $field_name => $field_value) {
	        $email_message1.= $field_name.": ".$field_value."\n\n";
	        }
			$headers1 = 'MIME-Version: 1.0' . "\r\n";
			$headers1 .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	        $headers1 .= 'From: '.$email_from1."\r\n" .
                           'Reply-To: '.$email_from1."\r\n" .
                           'X-Mailer: PHP/' . phpversion();
                // send the email
			
            mail($emailto,"New Registration", $email_message1, $headers1) ;
            if($mail->ErrorInfo) { die($mail->ErrorInfo) ; }   
				
		header("location: register-success.php");

Open in new window

0
Comment
Question by:rinfo
15 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
It is a plain fact that you cannot be using that script to send email, since the script fails with a parse error.  When you want to get help with a working script, it's usually a good idea to post the script "as-is" instead of redacting it.  When scripts are shortened like this one, there is often important information that is lost in the cut-and-paste process.
what measure i have to take to prevent user mail going to junk.
Let's start with that one.  You should tell your community to "whitelist" the sending email address and domain.  Second, and this is more art than science, you should not send email messages that look like spam.  Use the client's name in the email message body.  Avoid sending a generic subject string like 'Thank-you' -- that is a sure signal for spam filters.  Avoid sending from a generic name at hotmail.com -- another sure signal for spam filters.  Instead, put meaningful information into the subject and use a genuine email address at your domain name.  You might also want to omit 'X-Mailer: PHP/' . 'phpversion()'; since that is a clear signal that this is an automated message (all spam messages are automated messages, even though not all automated messages are spam).  And finally, check the headers by sending one of the messages to yourself at your own Gmail account.  You can "show original" to look at the raw email message including all the headers.  You will be able to see if your hosting company is adding anti-spam messages to your outgoing email.  If they are doing that, you might want to consider using PhpMailer instead of mail().

In the case of the admin emails, there is not much I can tell you because the content of the message relies on external data and we cannot see that data.  However you can omit this part: if($mail->ErrorInfo) { die($mail->ErrorInfo) ; } because that relies on object-oriented notation, and there are no instances of the mail object in the code.  Instead, I would look at the code logic carefully (requires the full script!) and see if there is not some conditional if() structure or similar that is blocking access to the part of the code that sends the admin mail.  I would also remove the redirection at the bottom and instead use var_dump() to print out all of the variables involved in the admin mail.  Once you see the script logic and the content of the variables you will probably be able to see what's going awry.

See also http://php.net/manual/en/function.mail.php and read it with an eye for detail.

HTH, ~Ray
0
 
LVL 9

Author Comment

by:rinfo
Comment Utility
Hello Mr.Ray
Thanks for the insights and i appreciate that.
It is a plain fact that you cannot be using that script to send email, since the script fails with a parse error.
Maybe it did have parse error because i posted a part of the code.
But i can assure you its a fully working code and as i mentioned there is no problem in sending the first mail its receipt ok by the user.
However exactly same code when used to send information to admin fails and i am saying is failing because i am not receiving this mail .
My confusion is why first mail works ok and second one fails.
I am not using generic email like admin mail etc , its more like individual name like james.watt@gmail.com.I would try and use domain email id for admin mail.
In the case of the admin emails, there is not much I can tell you because the content of the message relies on external data and we cannot see that data.
I have var_dumped on two variables $messages ($messages  consist of data from post values ),$headers they are populated as intended and i can see the values there is nothing wrong in that.
I would post the entire php script once i am on my workstation.
0
 
LVL 4

Expert Comment

by:jmdl1983
Comment Utility
Do you have the
header("location: register-success.php");

Open in new window

run after each email?

You can only specify header location once if so.
0
 
LVL 9

Author Comment

by:rinfo
Comment Utility
No i am redirecting only after the second mail and is not used for first mail.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
I would post the entire php script once i am on my workstation.
That will be very helpful because then we will have the true line numbers and can give some step-by-step directions to help debugging.

Also, please refer to my profile page here, click the "About me" tab and find my email address.  You can put my email address in as the admin email.  I will post the entire contents of the test message you send me and we can look at the headers.
0
 
LVL 9

Author Comment

by:rinfo
Comment Utility
Yeah that sure would be a good plan.
I would register you as a user as well as mention your id in the admin mail.
But problem is admin are not recieving email and without email how can you see headers.
Maybe user mail that you would recieve could give you a clue.
BTW i have a doubt could it because in the first mail header is set and in subsequent mail it might be experiencing header already sent or something like that.
Besides can you suggest me some code that would be used for both the mail one after another. Some how or other i feel that if entire code sent from another script will work if it is sent alone.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
admin are not recieving email and without email how can you see headers
What we need to understand is why the admin is not receiving the email.  If you put my address in for the admin in your test case, I will be able to see once we get the email to work!  I do not need to see the user mail, only the admin email.

"Header already sent" has to do with HTTP protocol, not email.  It is not an issue in this script.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
You have several problems that I can see in addition to the script being incomplete.  If you are sending email 'from' a Gmail or Hotmail address and you are not sending thru those services, the receiving email client can tell that and some will reject your email because you are trying to send from an email address that is not valid from your server.  When I send email from my web site, I always send from an email address that is valid on my server.  Some services actually check to see if your email address is valid as well as checking to see if it matches your server.
0
 
LVL 9

Author Comment

by:rinfo
Comment Utility
Hello Dave
Thanks for the input.One of the reason i used hotmail because client has insisted that they would rather use their regular hotmail id for the admin mail as they seldom check their domain mail service despite my insistance that they should.

You have several problems that I can see in addition to the script being incomplete
I will be posting the entire script . Please do let me know what are the other problems besides using generic email id .
0
 
LVL 9

Author Comment

by:rinfo
Comment Utility
Hello Dave
Sorry for the haste reply. I understand you mentioned from mail id should be rather server mail id and not admin email id . And that should not be a problem with the clients since they will be using their hotmail to recieve email (to admin mail id).
Point noted and understood. I will implement that.
0
 
LVL 9

Author Comment

by:rinfo
Comment Utility
Here is the php script file i am using.
Please have a look at suggest me anything that you should find for making it a better and working script.
I am open to all suggestion.
Thanks
BTW Merry Christmas and hope i am not bothering you on your festivity.
register-exec.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@rinfo: Thanks for the Christmas wishes.  All the rest of my family is still asleep this morning, so we are enjoying the holidays each in our own ways!
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
Here is the script.  I have tidied it up a bit to align the control structures because it makes the code easier to read and understand, and it shows the programmer's intent in the logic.  Some comments by line number:

2. I have raised the error reporting level.  This will let us see if we are relying on any undefined variables.

92. You might want to learn about filter_var() and checkdnsrr() functions.  I don't know if the REGEX is correct or not, but since PHP now has these built-in functions we should use them.

94. Variable name appears to be wrong.

109.  I have changed the query result test to make a better error message.  This will work for testing, but you will want better error handling when you put this script into production.

123. See 109.

128. See 109.

131.  I removed the conditional tests for query results because these have been moved to 123 and 128.

147. You probably do not want this header.

151. This line appears to be irrelevant.

152. This is my email address.  After you have run this script, please post the output back here so I will know to check my email.  I will post the complete message with all headers here so we can see what is going wrong.

162. See 147.

<?php // RAY_temp_rinfo.php
error_reporting(E_ALL);
session_start();
$errmsg_arr = array();
$errflag = false;


$link = mysql_connect("mysql.abc.com","abc","abc"); //credential are ficticious
if(!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

$db = mysql_select_db("dbacc");
if(!$db) {
    die("Unable to select database");
}


function clean($str) {
    $str = trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}


$fname          = clean($_POST['firstname']);
$lname          = clean($_POST['lastname']);
$gender         = clean($_POST['Gender1']);
$age            = clean($_POST['age']);
$qualification  = clean($_POST['Qualification1']);
$specialization = clean($_POST['Specialization1']);
$profession     = clean($_POST['Profession1']);
$institution    = clean($_POST['Institution']);
$city           = clean($_POST['City']);
$zipcode        = clean($_POST['Zipcode']);
$contactnumber  = clean($_POST['ContactNumber']);
$country        = clean($_POST['Country']);
$email          = clean($_POST['email']);
$login          = clean($_POST['login']);
$password       = clean($_POST['password']);
$datejoin       = time();

$datejoined     = date("d-m-y",$datejoin);
$confirmkey     = md5(uniqid(rand()));



//Input Validations
if($fname == '') {
    $errmsg_arr[] = 'First name missing';
    $errflag = true;
}
if($lname == '') {
    $errmsg_arr[] = 'Last name missing';
    $errflag = true;
}
if($gender == '') {
    $errmsg_arr[] = 'Gender is  missing';
    $errflag = true;
}
if($qualification == '') {
    $errmsg_arr[] = 'Qualificatio not mentioned';
    $errflag = true;
}
if($profession == '') {
    $errmsg_arr[] = 'Profession is not mentioned';
    $errflag = true;
}
if($specialization == '') {
    $errmsg_arr[] = 'Specialization is not mentioned';
    $errflag = true;
}
if($country == '') {
    $errmsg_arr[] = 'Country Name is not mentioned';
    $errflag = true;
}
if($email == '') {
    $errmsg_arr[] = 'Email has not been mentioned';
    $errflag = true;
}
if($login == '') {
    $errmsg_arr[] = 'Login ID missing';
    $errflag = true;
}
if($password == '') {
    $errmsg_arr[] = 'Password missing';
    $errflag = true;
}

if(! preg_match ( "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email )) {
    $errmsg_arr[] = 'Invalid Email Address';
    $errflg = true;
}

//Check for duplicate login ID
$qry = "SELECT count(*) AS c FROM authuser WHERE uname='$login'";
$result = mysql_query($qry);
if($result) {
    $result_array = mysql_fetch_assoc($result);
    if($result_array['c'] > 0) {
        $errmsg_arr[] = 'Login ID already in use';
        $errflag = true;
    }
    mysql_free_result($result);
}
else {
    die("FAIL: $qry BECAUSE: " . mysql_error());
}

//If there are input validations, redirect back to the registration form
if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: register-form.php");
    exit();
}

//Create INSERT query
$qry = "INSERT INTO signup VALUES (DEFAULT ,'$fname','$lname','$email','$age','$gender','$qualification','$profession','$specialization','$institution','$city','$zipcode','$contactnumber','$country','$login',$datejoined,'$confirmkey')";
$result = mysql_query($qry);
if (!$result) die("FAIL: $qry BECAUSE: " . mysql_error());


$qry1 ="INSERT INTO authuser VALUES(DEFAULT,'$login','$password','ungrouped',999,'Active',$datejoined,0)";
$result1 = mysql_query($qry1);
if (!$result1) die("FAIL: $qry1 BECAUSE: " . mysql_error());


$email_from = 'abcadmin@abc.com';
$email_message ='
<html>
<body>
Thank you very much for visiting our web site and your interest in Purohit Technique of Vaginal Hysterectomy.<br />
We offer Hands On Training on Vaginal Hysterectomy And Salpingo oophorectomy.
For complete details about the training and register please
<a href="http://www.purohittechnique.com/courses.php">click here</a>
</body>
</html>
';

$headers  = "MIME-Version: 1.0" .  "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= ' From: '.'admin@abc.com'."\r\n" .
'Reply-To: '.$email_from.'\r\n' .
'X-Mailer: PHP/' . 'phpversion()';
mail($email,'Thank-you', $email_message, $headers);


$headers1 = '';
$emailto  = "ray.paseur@gmail.com";
$email_from1 = $_POST['email'];
$email_message1 = "A new user having following details has registered on ".date("Y-m-d")." at ".date("H:i")."\n\n";
foreach($_POST as $field_name => $field_value) {
    $email_message1.= $field_name.": ".$field_value."\n\n";
}
$headers1 = 'MIME-Version: 1.0' . "\r\n";
$headers1 .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers1 .= 'From: '.$email_from1."\r\n" .
'Reply-To: '.$email_from1."\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($emailto,"New Registration", $email_message1, $headers1) ;

// WHILST DEBUGGING, DO NOT REDIRECT
// header("location: register-success.php");
// exit();

Open in new window

Let's try those things and see what you get.  Best regards, ~Ray
0
 
LVL 9

Author Closing Comment

by:rinfo
Comment Utility
Yes its working ok now .
I did made changes as suggested by Mr.Ray.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Glad things are looking up!  Thanks for using EE, and Happy New Year 2013!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article will show, step by step, how to integrate R code into a R Sweave document
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now