Friday, May 30, 2014

How to catch emails sent with PHP on your local server


Taking the idea from Martin Valasek.
I decided to make a small change like add the extension "*.eml" for opening faster the saved emails with thunderbird at the time they are created.
Create a folder for your outgoing mail. We will create it in under /var/log/ where all the logs are stored:
$ sudo mkdir /var/log/mail

Create file /usr/local/bin/sendmail using your favorite text editor
$ sudo nano /usr/local/bin/sendmail
Add following PHP script to this new "sendmail" file:
#!/usr/bin/php
<?php
$input = file_get_contents('php://stdin');
$timeCreated = explode(" ",microtime());
$filename = tempnam('/var/log/mail',$timeCreated[1].'_'.$timeCreated[0].'_');
file_put_contents($filename.'.eml', $input);
unlink($filename);
shell_exec('thunderbird '.$filename.'.eml > /dev/null 2>/dev/null &');

 We need to link our PHP script to PHP's sendmail functionality. Edit your "php.ini" file and set the sendmail_path setting as following:
sendmail_path = /usr/local/bin/sendmail
In Ubuntu the "php.ini" is located for Apache
/etc/php5/apache2
and for Cli
/etc/php5/cli

Now we need to set permissions for new files/folders:
$ sudo chmod 755 /usr/local/bin/sendmail
$ sudo chmod 777 /var/log/mail

Restart apache:
$ sudo /etc/init.d/apache2 restart
You can now try to send an email using PHP's mail() function and check the /var/log/mail folder.
And the email will open automatically with Thunderbird when they are created.

No comments:

Post a Comment