-
-
Save sharapeco/043fb492d8cc07ae8b36d498142bab22 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
function filenameFilter($subject) { | |
return preg_replace('/_{2,}/', '_', trim(preg_replace('/[^a-z0-9ぁ-ゟァ-ヿ一-龠-]/iu', '_', $subject), '_')); | |
} | |
// エラー→例外 ハンドラを登録する | |
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__' => filenameFilter($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