The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/perl -w

=head1 NAME

mimeprint - parse a MIME stream, and print the parsed entity

=head1 SYNOPSIS

    mimeprint
        Give usage.
     
    mimeprint [options] infile
        Parse a MIME stream from infile (- means stdin), and print 
        entity to stdout.

=head1 DESCRIPTION

Parse a MIME stream, and output the resulting entity.  This is
a nice way of eyeballing whether or not MIME-tools "understood"
your MIME message.

Due to nonuniqueness of MIME encodings, there is a very good chance
that your output will not I<exactly> resemble your input.    

=head1 AUTHOR

Eryq, eryq@zeegee.com

=cut

use lib "./lib";
use strict;
use Getopt::Std;

use vars qw($opt_d $opt_e $opt_h $opt_n $opt_v $opt_s $opt_u);
use MIME::Parser;

# Usage?
$ARGV[0] or die <<EOF;

Usage:
    mimeprint [-options] infile
       Parse a MIME stream from infile, and print entity to stdout:
          -d DIR       Output parts to disk under this directory.
          -v           Verbose output (debugging)
          -e ENCODING  Re-encode top-level entity (if not multipart)
          -s           Just print the skeleton
                    
          -h           Decode headers
          -n HOW       Parse nested messages [NEST or REPLACE]
          -u           Parse uuencode.

EOF

# Args:
getopts("d:hsve:n:u");
MIME::Tools->debugging($opt_v);

# Set up parser:
my $parser = new MIME::Parser;
if ($opt_d) {
    $parser->output_to_core(0);
    $parser->output_under($opt_d);
}
else {
    $parser->output_to_core('ALL');
}
$parser->extract_nested_messages($opt_n) if defined($opt_n);
$parser->extract_uuencode($opt_u || 0);
$parser->decode_headers($opt_h || 0);
$parser->ignore_errors(1);

# Parse:
my $ent = $parser->parse_open($ARGV[0]);
$ent or die "MIME parsing failed!\n";
print STDERR $parser->results->msgs;
if ($opt_e and !$ent->is_multipart) {
    supported MIME::Decoder $opt_e or die "unsupported encoding: $opt_e\n";
    $ent->head->mime_attr("Content-transfer-encoding" => $opt_e);
}
($opt_s ? $ent->dump_skeleton(\*STDOUT) : $ent->print(\*STDOUT));

1;