I had been re-configuring and re-developing some PHP code that I had for an idea for a networking site.
After moving servers to Bluehost, I uploaded the PHP code and re-configured and tested some of the code and it all worked OK apart from the PHP mail() function. It simply would not send out emails and after realising that the mail command was returning a FALSE value after execution, I went about finding out what was wrong, as the mail function had not seemed to have been changed since version PHP version 4.3.0 and I was using version 5.2.17
Simple code for sending emails that worked is as follows:
<?php $emailto = 'email@example.com'; $emailfrom = 'firstname.lastname@example.org'; $subject = 'Email Subject'; $messagebody = 'Hello.'; $headers = 'From: ' . $emailfrom.' . "\r\n" . 'Reply-To: ' . $emailto . ' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($emailto, $subject, $message, $headers); ?>
However, with the above example, the name of the sender and the name of the recipient aren’t included and even though my previous code worked on the old servers, Bluehost just did not like it and emails were not being sent.
Anyway, after 3 days of re-writing and re-formatting the most complex part of the code in the mail function, which is not actually that complex (the headers variable), with multiple emails backwards and forwards with Bluehost support (thanks guys and girls), and looking at how other scripts were sending out emails that worked, I eventually found a format that worked and sent out emails and included the from and to names, on Bluehost servers.
So, here’s the code. It’s not that complex but when you don’t know, you don’t know, until you do.
Please be careful with the syntax of the single and double quotes when creating the headers variable, which is what through out my code in the first instance.
<?php $emailto = 'email@example.com'; $toname = 'TO NAME'; $emailfrom = 'firstname.lastname@example.org'; $fromname = 'FROM NAME'; $subject = 'Email Subject'; $messagebody = 'Hello.'; $headers = 'Return-Path: ' . $emailfrom . "\r\n" . 'From: ' . $fromname . ' <' . $emailfrom . '>' . "\r\n" . 'X-Priority: 3' . "\r\n" . 'X-Mailer: PHP ' . phpversion() . "\r\n" . 'Reply-To: ' . $fromname . ' <' . $emailfrom . '>' . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Transfer-Encoding: 8bit' . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n"; $params = '-f ' . $emailfrom; $test = mail($emailto, $subject, $messagebody, $headers, $params); // $test should be TRUE if the mail function is called correctly ?>
NOTE: Some hosting companies disable sending email using the PHP mail() command so the above code may not work on such hosting. Ask your hosting company if or how it’s possible to send email using the PHP mail() function from your server.