Today I wasted 2 of my 5 available work hours pissing my life against a wall of imap_open problems.
I was trying to recurse through a POP3 mailbox, to do things with some automated alert emails.
But I kept seeing “imap_open(): Couldn’t open stream” errors. No matter what combination of host name, port, protocol, mailbox I used, I couldn’t connect.
{mail.my-isp-domain.com:110/pop3}INBOX // Doesn't work {mail.my-isp-domain.com} // Also doesn't work {mail.my-isp-domain.com:110}INBOX // Continued failure {mail.my-isp-domain.com/pop3}INBOX // Exasperation beginning to set in {wtf.wee.poo/damn} // FUUUUUUUUUUU*******KkkKKKKKKKK
So apparently many mail servers are configured oddly (I read that some require your username to be in the form ‘user=username@domain.com’, rather than the more correcterer ‘username@domain.com’, although that didn’t help me)…
In the end, what helped in my case (I’m absolutely sure YMMV) was that, even though I don’t think I’m connecting over SSL, I had to include “/novalidate-cert” in the server specification:
{mail.my-isp-domain.com:110/pop3/novalidate-cert} // Rocking (finally)
Annoying.
BUT the point of this post is… how I eventually stumbled on how to debug the problem.
The call to imap_open was wrapped in a try/catch block, which was ending execution of the code before I called imap_errors() to grab an array of errors relating to my imap_open() call.
What I had to do was (a) figure out that I might benefit from imap_errors(), and (b) add a call to that in the catch block that fielded the exception thrown when imap_open failed. I added the output of imap_errors() to the exception, and… that told me that the error stemmed from not being able to validate the server’s SSL certificate.
try { $connection = imap_open( $mailbox, $this->user, $this->password); } catch(Exception $e) { $imapErrors = implode("; ", imap_errors()); $message = $e->getMessage() . "\n\nIMAP ERRORS: {$imapErrors}"; throw new Exception($message); }
I’m making no claims about how good that is as code… but it at least forced a clue into the Exception, that allowed me to fix the problem.