Game Developer

PHP mail() function and GMail

Posted on

or Another reason to avoid PHP's mail() function

Since launching on Monday we've fixed a few bugs that only came to light as a result of the way other people work. One such was an email problem with messages sent to GMail (thanks to Alan for catching this). I've never had a GMail account so it wasn't one of the email applications we tested the messages with.

Email messages were arriving at GMail with messages garbled into a string of apparently random characters and with the sender listed as unknown. I was using mb_send_mail() to send UTF-8 email messages from PHP. I always intended to implement a different email solution at some point but evaluating the various possibilities and making a choice didn't seem as important for the launch period as many of the other features so I chose to start with mb_send_mail() and switch to another solution later.

mb_send_mail() was sending messages as UTF-8 and base64 encoded, and it seems that GMail failed to correctly understand this from the email headers. As a result, GMail simply displayed the base64 encoded data. The quick fix just to get it working was to switch to PHP's mail() function. This would suffice for a few hours while we sought a better solution.

The other problem was GMail displaying the sender as unknown, despite having the sender data in the From: header. I tried various different formats for the From: header (quotes around the name, extra spaces etc.) but none seemed to work for GMail. Instead, it always displayed the From: header line in the body of the message (there were no blank lines in the header so that's not the problem, and the messages worked with a number of other email applications we tested them with).

I still haven't discovered what the problem was but have three possibilities.

  1. Does GMail dislike the unconventional (but not technically wrong) ordering of the headers that mail() and mb_send_mail() produce?
  2. Does GMail distrust messages in which the X-Mailer header lists "PHP mailer" as the system used and consequently displays the sender as unknown and places the from data in the message?
  3. Is mail() doing something wrong in its headers, and most email applications are simply ignoring the mistake and figuring out what's intended?

If anyone knows the actual cause please add a comment below.

Anyway, the obvious solution was to avoid PHP's mail functions altogether so I hurriedly added Chris Corbyn's Swift Mailer script and altered my code to use it, and all was well. I haven't thoroughly tested Swift Mailer yet but it seems to be working fine - the messages are in UTF-8 and GMail is happy with them.

Swift Mailer is just one of many alternatives to the mail() function but I like it for it's simplicity of use. Hopefully, when I test it out more thoroughly later this month I'll still be very happy with it.

Share this post or a comment online -

Also in the collection PHP