Skip to content

Instantly share code, notes, and snippets.

@cdukes
Created April 13, 2015 15:41
Show Gist options
  • Save cdukes/e21d8b825cc2430b8e26 to your computer and use it in GitHub Desktop.
Save cdukes/e21d8b825cc2430b8e26 to your computer and use it in GitHub Desktop.
Catch emails from PHP and write them to a file
sendmail_path = /path/to/sendmail.php
#!/usr/bin/php
<?php
// Based on http://martinvalasek.com/blog/how-to-catch-emails-sent-with-php-on-your-local-server
// Get email content
$input = file_get_contents('php://stdin');
// Get 'To' address
preg_match('/To: (.+)/', $input, $matches);
// Build filename
$filename = '/path/to/destination/' . $matches[1] . '.html';
// If email is HTML, comment out the header
preg_match('/Content-Type: (.+?);/', $input, $matches);
if(
isset($matches[1]) &&
'text/html' === $matches[1] &&
strpos($input, '<!DOCTYPE html>') !== false
) {
$input = '<!--' . "\n" . $input;
$input = str_replace('<!DOCTYPE html>', '-->' . "\n" . '<!DOCTYPE html>', $input);
}
// Write file
$file = fopen($filename, "w");
fwrite($file, $input);
fclose($file);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment