I know with my cPanel hosting I can pipe an email inbox to a script, but what I want to do is:
Is there a way to do this with straight-forward PHP?
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.
You'll probably need do the following:
Write a PHP script that's executable at the CLI (by adding a #! declaration at the top of the script that points to the PHP binary, then settings its executable permissions).
Get that script to read the raw email from php://stdin (file_get_contents is easiest)
Get that script to decode the mail in to parts, using something like PEAR::Mail::Mime::Decode or I think there's a handy Zend Framework component).
Read the attachment and subject from the decoded message, and store as normal
exit(0) at the end to tell the CLI that it was a clean exit - any other exit() status could cause a bounced email.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With