There’ve been lots of times when I wanted to use the mail() function on my local server. I am sure lots of you would’ve been wanting it too but most of you would’ve settled for PHPMailer or just used a web host to test the code instead. I myself had been doing the same until recently when I finally decided to do some research and get it to work.
Here are the steps in short for the geeks who like to do things on their own:
All I did was used smtp client called msmtp, configured it to work with my gmail account and configured PHP to use msmtp to send emails.
This tutorial is only applicable for linux users. I’ll write another article for windows users soon when I get my hands on a windows box.
All the commands used in the instructions are for Ubuntu, however you may use corresponding commands for your distro (for eg; you can use yum install instead of apt-get install on fedora, redhat, centos.
Step by step instructions:
- First of all, follow this tutorial:
Install msmtp on your linux box and configure it to work with Gmail.Msmtp is highly configurable and you can easily configure it to work with any smtp server. If you wish to use any other service with msmtp, you may read its manual and configure it.
Proceed to next step only if you have successfully configured and are able to send a test message.
- Open php.ini in your text editor.
sudo gedit /etc/php5/apache2/php.ini
Search for ‘sendmail_path’ and change it to look like
sendmail_path = '/usr/bin/msmtp -t'
Save the file and exit the text editor.
Please note that your msmtp path may vary if you are not using Ubuntu. You may find the path to executable by:
- Restart apache:
sudo /etc/init.d/apache2 restart
sudo /opt/lampp/lampp restart
- Everything’s done. Lets test if the mail() function is working now:
if ( mail ( '[email protected]', 'Test mail from localhost', 'Working Fine.' ) ); echo 'Mail sent'; else echo 'Error. Please check error log.';
Replace the [email protected] with your own username, save it into a php file along with php delimeters in your virtual host root folder and execute it through the browser. You should receive a mail.
Give yourself a pat on the back.
Some points to note:
- If you weren’t able to send yourself a test mail in Step 1 ie. setting up msmtp, you should look at the debug information and search for solutions accordingly on the internet. Here’s the manpage of msmtp to help you with configuration
- If you didn’t receive a mail in your inbox on the last step, check in your Spam folder. If its not there your should check the php error log for hint about what went wrong and act accordingly.
- For any other questions, suggestions or appreciation feel free to use the comment box.