There exists a PHP library, called php-mime-mail-parser
which itself depends on the PECL mailparse library. When you have those installed, the code to achieve what you want is quite straight forward:
<?php
require_once 'MimeMailParser.class.php';
$parser = new MimeMailParser();
$parser->setStream(STDIN);
$subject = $parser->getHeader('subject');
$attachment_content = false;
foreach ($parser->getAttachments() as $attachment) {
$extension = pathinfo($attachment->filename, PATHINFO_EXTENSION);
if ($extension == "txt") {
$attachment_content = $attachment->content;
break;
}
}
// adapt to what ever database you are using
$sth = $mysqli->prepare("INSERT INTO mails (subject, attachment) VALUES (:subject, :attachment)");
$sth->bindParam(':subject', $subject, PDO::PARAM_STR);
$sth->bindParam(':attachment', $attachment_content, PDO::PARAM_STR);
$sth->execute();
You can pipe the mail into the script, as it reads from STDIN
. You can also read from a file by changing setStream
to setPath
. See the documentation of the library.