Here's a quickly cobbled together script I was using for processing attachments of a special email account:
(some steps and code redacted, for example parts that remember already processed messages and remove messages from the server after a number of days)
#!/usr/local/bin/php5
<?php
error_reporting(E_ALL);
date_default_timezone_set('Asia/Tokyo');
define('TYPE_TEXT', 0);
define('TYPE_MULTIPART', 1);
define('TYPE_MESSAGE', 2);
define('TYPE_APPLICATION', 3);
define('TYPE_AUDIO', 4);
define('TYPE_IMAGE', 5);
define('TYPE_VIDEO', 6);
define('TYPE_OTHER', 7);
define('ENCODING_7BIT', 0);
define('ENCODING_8BIT', 1);
define('ENCODING_BINARY', 2);
define('ENCODING_BASE64', 3);
define('ENCODING_QUOTEDPRINTABLE', 4);
define('ENCODING_OTHER', 5);
$server = 'example.com:110';
$user = 'foo';
$password = 'bar';
echo "
Logging in to $server with user $user...
";
$mbox = imap_open('{' . $server . '/pop3}INBOX', $user, $password);
if (!$mbox) {
die("Couldn't establish a connection.
" . join("
", imap_errors()));
}
$numMessages = imap_num_msg($mbox);
echo "Found $numMessages messages in inbox.
";
for ($i = 1; $i <= $numMessages; $i++) {
echo "
Processing message $i...
";
$header = imap_headerinfo($mbox, $i);
if (!$header) {
die("An error occurred while processing message $i.
" . join("
", imap_errors()));
}
echo "Message id: {$header->message_id}
";
$structure = imap_fetchstructure($mbox, $i);
if (!$structure) {
die("An error occurred while processing the structure of message $i.
" . join("
", imap_errors()));
}
if ($structure->type !== TYPE_MULTIPART || empty($structure->parts)) {
echo "Couldn't find any attachments to process, moving on...
";
continue;
}
echo "Message has " . count($structure->parts) . " parts, beginning processing of individual parts...
";
foreach ($structure->parts as $index => $part) {
$index++;
echo "Processing part $index with type of {$part->type}...
";
if ($part->type === TYPE_TEXT) {
echo "Part is plain text, moving on...
";
continue;
}
$bodypart = imap_fetchbody($mbox, $i, $index);
echo "Fetched part with length of " . strlen($bodypart) . " bytes, encoded in {$part->encoding}.
";
switch ($part->encoding) {
case ENCODING_BASE64 :
echo "Decoding attachment from BASE64.
";
$bodypart = imap_base64($bodypart);
break;
case ENCODING_QUOTEDPRINTABLE :
echo "Decoding attachment from Quoted-Printable.
";
$bodypart = imap_qprint($bodypart);
break;
}
$filename = $header->message_id . '_part_' . $index;
if (!empty($part->parameters)) {
foreach ($part->parameters as $param) {
if ($param->attribute == 'NAME') {
$filename = $param->value;
echo "Using original filename '$filename'.
";
break;
}
}
}
// file processing here...
}
echo "Done processing message $i.
";
}
imap_close($mbox);
echo "
Done.
";
Hope this serves as a starting point for you. Unless you can provide a more specific purpose of what you're looking for, it's probably just easy to come up with a script yourself.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…