Redirect Sendmail to File

Redirect email to file

Please note that this guide is for PHP

During development we do not necessarily want to really send email to our recipient unless we are testing an actual email module itself, most of the time in development we just want to log or dump somewhere that email notification. The following steps will guide you to dump the email to a certain .htm file viewable through  an internet browser.

Step 1: Modify the php.ini, in my case in etc/php/7.4/apache2/ folder. Look for the following entry:

      // smtp_port = 25    //comment this

      // SMTP = localhost  //comment this

      sendmail_path = /usr/local/bin/phpsendmail

Step 2: create a file phpsendmail (note: .php extension is omitted) in /usr/local/bin as our backend script and save the following content:

#!/usr/bin/php
<?php
        $logfile = '/var/www/html/other/mail_log/maillog.htm';
        if(file_exists($logfile) && filesize($logfile) >= 512000)
        {  // Delete 5K size
           unlink($logfile);
        }
        // Get the email content
        $log_output = "<br/>[" . date('Y-m-d H:i:s') . "] ";
        $handle = fopen('php://stdin', 'r');
        $count = 0;
        while(!feof($handle))
        {
                $count++;
                $buffer = trim(fgets($handle));
                if ($count <= 12) # Output header information
                        $log_output .= $buffer . ",";
                else # Output body
                        $log_output .= $buffer;
        }
        // Write the log
        file_put_contents($logfile, $log_output, FILE_APPEND);
?>

       and execute this in your terminal: sudo chmod 755 /usr/local/bin/phpsendmail

Step 3: create a file maildump.php as our frontend script where your web server document path is located (in my case var/www/html).

<?php
        echo "Sending log to mail_log/maillog.htm file";
        $name = "mail dump"; //senders name 
        $email = "admin@localhost.com"; //senders e-mail adress 
        $recipient = "customer@localhost.com"; //recipient 
        $mail_body = "This is a test email."; //mail body 
        $subject = "Test Email"; //subject 
        $header = "From: ".$name . " &#60;" . $email . "&#62;"; //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.';    
?>

Step 4: Create a folder var/www/html/mail_log/ as the storage maillog.htm of the email and make sure you execute this file sudo chmod 777 var/www/html/mail_log to make the folder writable.

How To's mail