php mail fails after working

Hi:

I had mail() working in my registration script. The testers started, and the first tester got the activation email message correctly on their gmail account that they registered with. It contains the activation code and URL to enter their email address, pw and this code.

When the second tester registered using their gmail account, they did not receive the email. So I tested the script by registering myself using one of my gmail accounts and it failed, which is odd since it worked previously.

So I scripted a simple mail() as follows:
<?php
// Emailing test

$to = "my.name@gmail.com";
$subject = "Subject: This is the subject";
$message = "This is the message";
$headers = "From: support@example.com"."\r\n"."Reply-to: support@example.com"."\r\n";

mail($to, $subject, $message, $headers);

echo "mailed";
?>

Open in new window


and it failed.
Here are the php.ini mail settings which I have never changed from the default on my shared server:
;php.ini

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path =

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =

; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header = On

; Log all mail() calls including the full path of the script, line #, to address and headers
;mail.log =

Open in new window


I made sure that I whitelisted my site and the support email address on gmail. When I send identical data from my personal email to the one used by my site, it is accepted.

Any ideas?
Torquil BeavisBusinessAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jason C. LevineDon't talk to me.Commented:
What are you defining as "fail" here?  Are you actually seeing an error in the error_log to indicate a failure or is the mail just not showing up?

If the latter, it's probably more likely that proceduely generated email sent directly from the server is being spam-trapped by something before it ever gets to Google and to your personal settings.  

I've basically stopped using the PHP mail() command for this reason and instead I sign up all sites I work on for Mandrill (mandrill.com) and use them as the sending server.  With Mandrill and properly configured SPF and DKIM records you will see almost perfect delivery rates.
0
Torquil BeavisBusinessAuthor Commented:
No errors that I can see in the log, and it fails to arrive at the gmail address.
0
Dave BaldwinFixer of ProblemsCommented:
Email from web sites is often automatically considered spam and just dropped.  Hotmail does that when I try to send from a web page on Godaddy.  I can use the same 'From:' address in an email from the web site and another thru a 'regular' email account and the one from the web disappears and the one from the 'regular' account goes thru.  

You could possibly get NDRs if support@example.com was an actual email account where you could receive them.  In addition, your test email does not have 'adequate' headers.  Below is my email demo.  Put in your own email account and see if it works for you.
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');

# some settings of POST vars
if (!isset($_POST['submit']))  $submit = ''; else $submit = $_POST['submit'];
if (!isset($_POST['subjectText'])) $subjectText = ''; else $subjectText = $_POST['subjectText'];
if (!isset($_POST['msgText'])) $msgText = ''; else $msgText = $_POST['msgText'];
if (!isset($_POST['ccText'])) $ccText = ''; else $ccText = $_POST['ccText'];
if (!isset($_POST['bccText'])) $bccText = ''; else $bccText = $_POST['bccText'];
if (!isset($_POST['nameText'])) $nameText = ''; else $nameText = $_POST['nameText'];
if (!isset($_POST['fromText'])) $fromText = ''; else $fromText = $_POST['fromText'];

if ($submit == "") {
    $title="Test Email Page";
    $announce="---";
}
else {
	if($fromText === "") die("No name!");
  $toText="youremail@yourdomain.com";
	$title="Test Email Page";
  $announce="Your Message has been Sent!";
	$header = "From: ".$fromText."\r\n";
//	$header .= "Cc: ".$ccText."\n";
	$header .= "Reply-To : ".$fromText."\r\n";
	$header .= "Return-Path : ".$fromText."\r\n";
	$header .= "X-Mailer: PHP\r\n";
	$header .= "MIME-Version: 1.0\r\n";
	$header .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
//	ini_set(sendmail_from,$fromText);  
	mail($toText, $subjectText, $msgText, $header, '-f'.$fromText);
//	ini_restore(sendmail_from);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title><?php echo($title)?></title>
<style type="text/css">
<!-- 
A:link { color: #999999; }
A:visited { color: #999999; }
A:hover {color: #0099ff;}
-->
</style>
<script type="text/javascript">
<!--
function check()
{
var at=document.getElementById("fromText").value.indexOf("@");
var eml=document.getElementById("fromText").value;
var nam=document.getElementById("nameText").value;
var alerttxt="";
var submitOK="true";

if (eml.length < 5 || at == -1)
    {
    alerttxt=alerttxt+"Please enter a valid e-mail address!\r\n";
    submitOK="false"
    //return false;
    }
if (nam.length < 3)
    {
    alerttxt=alerttxt+"Please enter your name.\r\n";
    submitOK="false"
    //return false;
    }
if (submitOK=="false")
    {
    alert(alerttxt);
    return false;
    }

}
// -->
</script>
</head>

<body bgcolor="#ddeedd">
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" summary="" width="580">
<tr><td align="center">

<?php
if ($submit != "") {
   	echo ("To: ".$toText."<br>\r\nSubject: ".$subjectText."<br>\r\n".$msgText."<br>\r\n".$header);
		}
?>

<p><b><font color="#000000" size="5">Test Email</font></b></p>
<font size="4" color="#000000">

<form method="POST" action="Email.php" onsubmit="return check();">
    <p><font size="3"><b>Name: <input type="text" name="nameText" id="nameText" size="46"></b></font></p>
    <p><font size="3"><b>Email: <input type="text" name="fromText" id="fromText" size="46"></b></font></p>
    <input type="hidden" name="subjectText" value="Web Mail">
    <p><font face="Arial" size="3"><b>Message Text:</b></font></p>
    <p><font face="Arial" size="3"><b><textarea rows="6" name="msgText" cols="60"></textarea></b></font></p>
    <p><font size="3"><b><input type="submit" value="submit" name="submit" style="font-family: Arial; font-size: 12pt; font-weight: bold"></b></font></p>
    <input type="hidden" name="state" value="1">
  </form>
  <b><font face="Arial" size="4" color="#e00000"><?php echo($announce)?></font></b><br><br>

</font>
</td></tr>
</table> 
</div>

</body>
</html>

Open in new window

0
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

Dave BaldwinFixer of ProblemsCommented:
About headers:  It is typical that email from web sites don't use complete headers but email from 'regular' email clients always do.  Simple headers has been a sign of spam for many years.
0
Ray PaseurCommented:
Further to what Dave Baldwin says, "... typical that email from web sites don't use complete headers ..." or that the web host injects anti-spam headers into the mail header collection.  Many mail programs recognize this and dump the automated email.  Some ideas: Suggest to your clients that they whitelist the sending address.  Provide an online experience that does not require email, such as SMS (learn about Twilio).  Tell them they must send an email to your server's auto-responder (in some cases this will automatically whitelist the address and domain).

The nasty truth is that most people do not really want a lot of automated email, and the email infrastructure has become more and more hostile to automated email.  This is why companies like Constant Contact have a business -- they know how to get the messages to go through.  You might want to consider their free trial.
http://support2.constantcontact.com/articles/FAQ/1939
0
Torquil BeavisBusinessAuthor Commented:
Thanks guys.
I copied your script, Dave, and it replied 'sent', yet my gmail address did not receive it. Could this be a google gmail issue or perhaps a site blocking issue of some sort (I am verified by google's webmaster tools)?
0
Jason C. LevineDon't talk to me.Commented:
It's less of a site blocking issue and more of an IP or netblock issue. If you are on shared hosting or have a VPS at a large ISP that does not strictly police emails, it is likely that your IP or even the whole range of IPs has been blacklisted.
0
Dave BaldwinFixer of ProblemsCommented:
Interesting.  My email demo can't send from this computer to Gmail... but it works fine on my web hosting at Hurricane Electric.  Where is your web site and server located?  Are you on 'public hosting' or are you on your own computer on a residential account?

Note that the Cc: to one of my other email addresses went thru even when it did not go to Gmail.
0
Torquil BeavisBusinessAuthor Commented:
I'm on shared hosting out of BC, Canada. I don't use any VPS. It's odd that they'd blacklist since I only sent individual emails from the website, and only around 30 in total over the last 2 months. The last one to go through went to an email account that wasn't mine, then the failed one also went to an email that wasn't mine. I'd been testing the script for a while using my own 8 gmail accounts, then added 2 more for 2 more testers.
I'll check with the web host re IP blacklisting.
I'm using the email as an activation process only. All member communications will be through the Contact page and will be put onto DB.
0
Jason C. LevineDon't talk to me.Commented:
The ISP isn't blacklisting you.  The more likely scenario is that due to some bad behavior from another user of the shared hosting, the ISP itself is on or more spam blacklists. That would cause Google and others to kill any messages originating from the banned IPs without a properly authenticated SMTP account behind it.

Seriously, switch to PHPMailer or something else that supports SMTP authentication and use Mandrill for transactional emails.  It's free for up to 12,000 messages a month and reduces this headache to zero.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
Might also want to learn about this.  If you don't already use SPF headers you may want to try it.
http://en.wikipedia.org/wiki/Sender_Policy_Framework
0
Dave BaldwinFixer of ProblemsCommented:
Note that if you are on Godaddy hosting, PHPMailer isn't going to help you because they block all ports but port 25 and that is only available to connect to their mail servers.  You are essentially blocked from connecting to an outside mail server on other ports.
0
Jason C. LevineDon't talk to me.Commented:
Probably should be using 587 or one of the secure ports anyway...
0
Torquil BeavisBusinessAuthor Commented:
I'm not on GoDaddy. I checked for IP blacklisting and my site is ok.

I'm testing phpmailer. I checked all the variables with the web hosting company. I tried using the IP address instead of smtp.example.com. It failed. Follows is the script and fail message ..
<?php

require_once('includes/class.phpmailer.php');
include('includes/class.smtp.php'); // optional, gets called from within class.phpmailer.php if not already loaded

$mail             = new PHPMailer();

//$body             = file_get_contents('contents.html');
//$body             = eregi_replace("[\]",'',$body);
$body="Hello there!";

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "smtp.example.com"; // SMTP server      Alternatively, use smtp.example.com  OR IP address
$mail->SMTPDebug  = 3;                     // enables SMTP debug information (for testing)  -  >>>>>>>> change to 2 when testing done <<<<<<<<<<<
// 1 = errors and messages
// 2 = messages only
// 3 = verbose errors
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = 'none';
$mail->Host       = "smtp.example.com"; // sets the SMTP server    Alternatively, use smtp.example.com OR IP address
$mail->Port       = 587;                    // set the SMTP port
$mail->Username   = "example@example.com"; // SMTP account username
$mail->Password   = "abc123";        // SMTP account password
$mail->SetFrom("example@example.com", "Sally");
$mail->AddReplyTo("example@example.com", "Sally");
$mail->Subject    = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->Body = $body;
//$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
//$mail->MsgHTML($body);
$address = "my.accountname@gmail.com";
$mail->AddAddress($address, "krotb");
//$mail->AddAttachment("images/phpmailer.gif");      // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send())
{
    echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
    echo "Message sent!";
}
?>

Open in new window


And here's the error message ..
2015-04-07 21:29:21 Connection: opening to smtp.example.com:587, t=300, opt=array ( ) 2015-04-07 21:29:21 SMTP ERROR: Failed to connect to server: Connection refused (111) 2015-04-07 21:29:21 SMTP connect() failed. Mailer Error: SMTP connect() failed.      

Open in new window


All ideas welcome.
0
Dave BaldwinFixer of ProblemsCommented:
In place of 'smtp.example.com', you need to use a valid SMTP server address where your username and password are valid.  You also need to verify that port 587 is an acceptable port on that server.  All instances of 'example@example.com' need to be replaced with valid email addresses.
0
Torquil BeavisBusinessAuthor Commented:
According to the web host the smtp address is valid (not 'example' of course), since it's the mail server. They confirmed that my username and pw are correct; and they emphasized 587 as the port for outgoing email. Also, the email addresses are all valid/real (not 'example'). I simply sterilized the code for this post ;)
0
Dave BaldwinFixer of ProblemsCommented:
Ok, just checking.  Can you send email thru that SMTP server with a regular email client?
0
Torquil BeavisBusinessAuthor Commented:
I sent an email from my personal gmail account to the web site support@example.com which also forwards to another gmail account. 100% success. This makes it seem as if the script has an error, like a missing parameter or invalid value, that's preventing it connecting. Or am I missing something here?
0
Torquil BeavisBusinessAuthor Commented:
So I tried an example of a phpmailer for gmail where I used 'to' and 'from' gmail addresses, and still got a fail:
<?php

require_once('includes/class.phpmailer.php');
include('includes/class.smtp.php'); // optional, gets called from within class.phpmailer.php if not already loaded

define('GUSER', 'example1@gmail.com'); // GMail username
define('GPWD', 'password'); // GMail password FOR example@gmail.com

$mail = new PHPMailer();

$body="Hello there!";
$from = "example1@gmail.com";
$from_name = "James";
$subject = "This is a test gmail";
$body = "Using the gmail phpmailer";
$to = "example2@gmail.com";

$mail = new PHPMailer();  // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);

if(!$mail->Send())
{
    echo 'Mail error: '.$mail->ErrorInfo;
}
else
{
    echo 'Message sent!';
}
?>

Open in new window


Error:
Mail error: SMTP connect() failed.

Open in new window


This does not use any of the website's email addresses, yet still failed.
0
Jason C. LevineDon't talk to me.Commented:
It's not the web site's address or any email address, but something about the SMTP server not liking the connection or needing authentication before it will send email (check before send).

Hate to sound like a broken record, but this is why using a third-party SMTP tends to work better.  Can you reconfigure the script to use Gmail's SMTP servers and see if it works better
0
Torquil BeavisBusinessAuthor Commented:
Is this what you mean, Jason?

<?php

require_once('includes/class.phpmailer.php');
include('includes/class.smtp.php'); // optional, gets called from within class.phpmailer.php if not already loaded

define('GUSER', 'my.gmail@gmail.com'); // GMail username for google account
define('GPWD', 'password'); // GMail password

$mail = new PHPMailer();

$body="Hello there!";
$from = "support@example.com"; // where example.com is my website
$from_name = "James";
$subject = "This is a test gmail";
$body = "Using the gmail phpmailer";
$to = "member@gmail.com";

$mail = new PHPMailer();  // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);

if(!$mail->Send())
{
    echo 'Mail error: '.$mail->ErrorInfo;
}
else
{
    echo 'Message sent!';
}
?>

Open in new window


This was the response:
Mail error: SMTP connect() failed.

Open in new window


I believe this script is using Gmail's SMTP server. Did I misunderstand what you meant?
0
Jason C. LevineDon't talk to me.Commented:
Yes, correct.  However, switch the FROM account to be from your Gmail address to get through Gmail's security.  Also set SMTPDebug to 1 to get more info.
0
Torquil BeavisBusinessAuthor Commented:
This is what I ran .. still failed .. message below

<?php

require_once('includes/class.phpmailer.php');
include('includes/class.smtp.php'); // optional, gets called from within class.phpmailer.php if not already loaded

define('GUSER', 'my.gmail@gmail.com'); // GMail username for google account
define('GPWD', 'password'); // GMail password

$mail = new PHPMailer();

$body="Hello there!";
$from = "my.gmail@gmail.com";
$from_name = "James";
$subject = "This is a test gmail";
$body = "Using the gmail phpmailer";
$to = "member@gmail.com";

$mail = new PHPMailer();  // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;  // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);

if(!$mail->Send())
{
    echo 'Mail error: '.$mail->ErrorInfo;
}
else
{
    echo 'Message sent!';
}
?>

Open in new window

2015-04-08 19:11:36 SMTP ERROR: Failed to connect to server: Connection refused (111) 2015-04-08 19:11:36 SMTP connect() failed. Mail error: SMTP connect() failed.

Open in new window

0
Jason C. LevineDon't talk to me.Commented:
It's weird that all methods are failing.  Something should work...

Run your site IP through this:

http://mxtoolbox.com/blacklists.aspx
0
Torquil BeavisBusinessAuthor Commented:
Ok, I checked the mxtoolbox site and it's green from all 89 blacklists.

mail() was working in my script while testing. Then I got two non-IT testers to run the site. The first one got the email, while later that day, the second one did not get the email. It was around the time that gmail had major issues supposedly for a few hours.
0
Torquil BeavisBusinessAuthor Commented:
Thought: Could there be php.ini parameter settings that are preventing the connection to the server?
Or permissions somewhere, perhaps?
0
Torquil BeavisBusinessAuthor Commented:
Could a redirect from non-SSL to SSL in .htaccess cause this issue? OK, I'm over the edge of the envelope now (since it worked before). Browsed through the net and can't find anything that could lead to this. Does the (111) error give a hint?
0
Jason C. LevineDon't talk to me.Commented:
No, it's not an .htaccess issue.  It may be something in PHP.ini or it could be an ISP issue.  We've kind of reached the limit on what it we can do without direct access to the server.

The scripts looked correct, this should have worked...
0
Torquil BeavisBusinessAuthor Commented:
It's working now.

I had family in from abroad with their 4 devices (plus our 5). Two of them were testers. All went well until one of the testers didn't get the email in question.

In a state of complete frustration with this (and I know you empathize), and since family have now left, I turned off the router and computer, then powered up again. I tested the email() in the app and it worked perfectly across emails from the website (using the original mail()).  

I take from this that the router was somehow corrupting the emailing. Any ideas why?

Clearly, I'm going to take your advice and use phpmailer since I don't need unexpected email failures from any source.
0
Jason C. LevineDon't talk to me.Commented:
I take from this that the router was somehow corrupting the emailing. Any ideas why?

Beats the heck out of me.  Maybe Dave or Ray have an idea, but this should not have happened...
0
Torquil BeavisBusinessAuthor Commented:
Since I'm new to experts exchange, do I need to post anew for help with phpmailer (since it's throwing up an error I don't understand), in order to replace mail() with phpmailer in my app?
0
Jason C. LevineDon't talk to me.Commented:
I would.  This site works best as one question per thread.  Once it gets more than a couple of days old, it's harder to get new eyeballs in here.  Posting a new question sends new alerts to all available Experts in the topic and gets more help, faster.
0
Torquil BeavisBusinessAuthor Commented:
All of your helps showed me what the issue was not, which was good. Much appreciated guys.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Email Protocols

From novice to tech pro — start learning today.