Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/*
メールをディスクに保存する
Based on rudiedirkx/mailtodisk.php
https://gist.github.com/rudiedirkx/ae893b4041aadda70d42
[php.ini]
sendmail_path = "C:\Server\php72nts\php.exe C:\Server\mailtodisk.php \"C:\Server\var\mailoutput\__TIME__-__RAND__-__SUBJECT__.eml\""
sendmail_path = "/usr/bin/php /var/www/mailtodisk.php \"/var/www/mailoutput/__TIME__-__RAND__-__SUBJECT__.eml\""
*/
const DateFormat = 'Ymd-His-v';
function putLog($message) {
file_put_contents(__DIR__ . '/mailtodisk.log', $message . PHP_EOL, LOCK_EX | FILE_APPEND);
}
// エラー→例外 ハンドラを登録する
set_error_handler(
function ($errno, $errstr, $errfile, $errline) {
// エラーが発生した場合、ErrorExceptionを発生させる
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
},
(E_ALL | E_STRICT) | (~E_WARNING));
try {
putLog(date('[Y/m/d H:i:sO]'));
// putLog(print_r($_SERVER, 1));
// Destination folder/filename is required
$destination = @$_SERVER['argv'][1];
if (!$destination) {
putLog('ERROR: Missing destination.');
exit(1);
}
// Create target folder
$dir = dirname($destination);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
if (!is_dir($dir)) {
putLog('ERROR: Invalid destination.');
exit(2);
}
// Get entire mail content
$mail = file_get_contents('php://stdin');
// putLog($mail);
// Extract subject
$subject = 'NO SUBJECT';
if (preg_match('#Subject:\s+([^\r\n]+)#', $mail, $match)) {
if (is_callable('imap_utf8')) {
$subject = imap_utf8($match[1]);
} else if (is_callable('mb_decode_mimeheader')) {
$subject = mb_decode_mimeheader($match[1]);
} else {
putLog('ERROR: MIME decode function does not exist.');
exit(3);
}
}
// Create filename with wildcards
$now = new DateTime();
$destination = strtr($destination, [
'__TIME__' => $now->format(DateFormat),
'__RAND__' => substr(md5(rand()), 0, 8),
'__SUBJECT__' => preg_replace('#_{2,}#', '_', trim(preg_replace('#[^a-z0-9-]#i', '_', $subject), '_')),
]);
putLog('Destination: ' . $destination);
file_put_contents($destination, $mail);
exit(0);
} catch (Exception $e) {
putLog('ERROR: ' . $e->getMessage());
putLog($e->getTraceAsString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.