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


#!/usr/bin/php
<?php
	$logfile = '/data/www/ap/sent-mail.htm';
	//* Get the email content
	$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);
?>

Then, edit your php.ini (mine is here: /etc/php5/apache2/php.ini) so that the mail portion of the file looks like this (note the commented-out lines and the sendmail_path):


[mail function]
; For Win32 only.
; http://php.net/smtp
; SMTP = localhost
; http://php.net/smtp-port
; smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
; sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
; sendmail_path =
sendmail_path = /usr/local/bin/phpsendmail

Restart apache (mine restarts with: sudo /etc/init.d/apache2 restart)

Now send a test email using your php script. If you want, you can create this file in your www root and run it:

<?php
  $name = "From PHP"; //senders name 
  $email = "testfromaddress@domain.edu"; //senders e-mail adress 
  $recipient = "testsenttoaddress@domain.edu"; //recipient 
  $mail_body = "The text for the mail...rnhi... this is the second line of the body text.rnThirdrnand fourth lines."; //mail body 
  $subject = "Subject for reviever"; //subject 
  $header = "From: ". $name . " <" . $email . ">rn"; //optional headerfields 

  echo date('h:i:s A') . ' *** ';
  if (mail($recipient, $subject, $mail_body, $header) === true)
    echo 'Mail sent successfully.'; 
  else
    echo 'Mail could not be sent.';
?>


Now you should have a sent-mail.htm in your www root! Browse to it with your web browser!

The following script and idea is modified from this website: http://www.howtoforge.com/how-to-log-emails-sent-with-phps-mail-function-to-detect-form-spam

Leave a Reply

Your email address will not be published. Required fields are marked *