Send email from PHP to a log file instead of sendmail

From Brian Nelson Ramblings
Jump to: navigation, search

Send email from PHP to a log file instead of sendmail

Say you want to test email sent from a PHP application on your development environment, and you don’t want to set up sendmail. You can write a little PHP script to replace the sendmail call!

First, create the following file: /usr/local/bin/phpsendmail

vim /usr/local/bin/phpsendmail

Then add the following code to the phpsendmail file

#!/usr/bin/php
 <?php
 	$logfile = '/var/www/html/protected-directory/mailoutbound.htm'; 
    	$log_output = "<p>****" . date('Y-m-d H:i:s') . "****</p>rn";
  	$handle = fopen('php://stdin', 'r');
 	$count = 0;
 	while(!feof($handle)) 
 	{
 		$count++;
 		$buffer = trim(fgets($handle));
 		if ($count <= 12) # Output header information
 			$log_output .= $count . ": " . $buffer . "<br>rn";
 		else # Output body
 			$log_output .= $buffer . "rn";
 	}
 	//* Write the log
 	file_put_contents($logfile, $log_output, FILE_APPEND);
 ?>

Now you will want to edit your php.ini or php-fpm pool file and set the sendmamil path

php.ini locate and replace

find:

sendmail_path => /usr/sbin/sendmail -t -i

replace with

sendmail_path = /usr/local/bin/phpsendmail

Next restart apache or php-fpm depending on your setup

/etc/init.d/apache restart

or

/etc/init.d/php-fpm restart

Now you can view the emails from your browser/text file via http://<domainn.tld>/protected-directory/mailoutbound.htm