Skip to content

Instantly share code, notes, and snippets.

@warewolf
Created August 7, 2012 14:25
Show Gist options
  • Save warewolf/3285790 to your computer and use it in GitHub Desktop.
Save warewolf/3285790 to your computer and use it in GitHub Desktop.
perl mail mangling
#!/usr/bin/perl
use MIME::Parser;
my $parser = new MIME::Parser;
my ($msg,$entity,$header,$head,%email);
open (MESSAGE,"<$ARGV[0]");
while (<MESSAGE>) { push (@{$msg},$_) };
close MESSAGE;
$parser->output_dir("mimemail");
$parser->output_prefix("part");
$entity = $parser->parse_data($msg) or die "couldn't read mime stream";
$header = $entity->head;
$header->unfold;
$email{from}=$header->get('From');
$email{to}=$header->get('To');
$email{subject}=$header->get('Subject')|| "No Subject";
$email{date}=$header->get('Date');
print "From : $email{from}";
print "To : $email{to}";
print "Date : $email{date}";
print "-------------------------\n";
print "Subject : $email{subject}";
&dump_entity($entity);
sub dump_entity {
my ($entity) = @_;
my (@parts,$part_num);
my $header = $entity->head;
my $body = $entity->bodyhandle;
my $IO_HANDLE;
$email{from} = $header->get('From');
$email{to} = $header->get('To');
$email{subject} = $header->get('Subject');
$email{date} = $header->get('Date');
my @parts = $entity->parts;
if (@parts) {
my $partnum;
foreach $partnum (0..$#parts) {
&dump_entity($parts[$part_num]);
}
} else {
my $IO_HANDLE;
my ($type,$sub_type) = split("/",$header->mime_type);
if ($type =~ /^text|message$/i)
{
if ( $IO_HANDLE = $body->open("r") ) {
my $content;
$content .= $_ while (defined($_ = $IO_HANDLE->getline));
print $content;
$IO_HANDLE->close;
}
} else {
print "\nContent-type: $type/$sub_type\n";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment