Show mime.pl syntax highlighted
#!/usr/bin/perl -w
use strict;
use lib qw(/home/tkay/src/alphamail/lib);
use MIME::Parser;
use MIME::Decoder;
use Encode;
use Data::Dumper;
use Middleware;
# Return the main body, preferring plain over html, returning undef if not
# found
sub find_main_body
{
my $part = shift;
my $html_body = undef;
my $body;
if(defined($part->{body}) && $part->{type} eq 'text') {
$html_body = $part if($part->{subtype} eq 'html');
return $part if($part->{subtype} eq 'plain');
}
if(defined($part->{children})) {
for my $c (@{$part->{children}}) {
$body = find_main_body($c);
return $body if(defined($body) && $body->{subtype} eq 'plain');
$html_body = $body if(defined($body) && $body->{subtype} eq 'html');
}
}
return $html_body;
}
sub parse_entity {
my ($entity, $name, $charset) = @_;
defined($name) or $name = "'anonymous'";
my $IO;
my $result = {};
$charset = $entity->head->mime_attr('content-type.charset') || 'us-ascii';
$result->{subject} = $entity->head->get('Subject');
$result->{date} = $entity->head->get('Date');
$result->{from} = $entity->head->get('From');
$result->{to} = $entity->head->get('To');
# Output the complete header, with mimewords dropped:
$result->{header} = Middleware::_mimewords_to_utf8($entity->head->original_text);
# Output the body:
my @parts = $entity->parts;
if (@parts) { # multipart...
my $i;
foreach $i (0 .. $#parts) { # dump each part...
$result->{children}[$i] = parse_entity($parts[$i], "", $charset);
}
}
else { # single part...
# Get MIME type, and display accordingly...
my ($type, $subtype) = split('/', $entity->head->mime_type);
my $body = $entity->bodyhandle;
$result->{subtype} = $subtype;
if ($type eq 'text') { # text: display it...
if ($IO = $body->open("r")) {
$result->{type} = "text";
$result->{body} .= encode('utf-8', decode($charset, $_)) while (defined($_ = $IO->getline));
$IO->close;
}
}
else { # binary: just summarize it...
my $path = $body->path;
my $size = ($path ? (-s $path) : '???');
$result->{type} = "attachment";
$result->{attachment}{file} = $path;
$result->{attachment}{size} = $size;
}
}
return $result;
}
my $parser = new MIME::Parser;
my $entity;
my $result;
$parser->output_under("tmp");
$parser->decode_headers(0);
$parser->ignore_errors(0);
$entity = $parser->parse_open("<mime.message");
$result = parse_entity($entity, "");
print Dumper($result);
See more files for this project here