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

	$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;
		$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.
; SMTP = localhost
; smtp_port = 25

; For Win32 only.
; sendmail_from =

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; 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:

  $name = "From PHP"; //senders name 
  $email = ""; //senders e-mail adress 
  $recipient = ""; //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.'; 
    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:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.