tags:

views:

28

answers:

2

I'm using the following php script to receive and process emails, putting the various pieces into variables to handle later on.

#!/usr/bin/php -q
<?php
// read from stdin
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);

// handle email

$lines = explode("\n", $email);

// empty vars

$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;

for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}

if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}

Im wondering where would i start in order to accept a picture attachment and isolate that into a variable so i can process it however i needed to.

A: 

You would need to do alot more than what you are doing. You have to detect the mime boundaries in the header, then find the multipart boundary and unbase64 the text. You would be much better off using a library for this sort of thing.

Byron Whitlock
thats what i was affraid of, off to google! thanks for the tip btw
Patrick
+1  A: 

I would use MimeMailParse (http://code.google.com/p/php-mime-mail-parser/) Then you could simply say

$parser = new MimeMailParser();
$parser->setStream(STDIN);

// Handle images
$path = '/tmp/';
$filename = '';
$attachments = $parser->getAttachments();
foreach ($attachments as $attachment) {
    if (preg_match('/^image/', $attachment->content_type, $matches)) {
        $pathinfo = pathinfo($attachment->filename);
        $filename = $pathinfo['filename'];

        if ($fp = fopen($path.$filename, 'w')) {
            while ($bytes = $attachment->read()) {
                fwrite($fp, $bytes);
            }
            fclose($fp);
        }
    }
}
David
nice find, ill look into this more
Patrick