开发者

Isolating picture attachment from email with php

开发者 https://www.devze.com 2022-12-13 01:44 出处:网络
I\'m using the following php script to receive and process em开发者_开发技巧ails, putting the various pieces into variables to handle later on.

I'm using the following php script to receive and process em开发者_开发技巧ails, 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.


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);
        }
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消