#!/usr/bin/perl -w

use MIME::Parser;
use File::Copy;
use Mail::Internet;
use Mail::Util qw(read_mbox);

# Global variables
my (@filterlist);
my ($msg_subject, $msg_from, $msg_to, $msg_replyto, $msg_cc, $msg_date);
my (%mimesave, %attachments);

if (@ARGV == 0) {push @ARGV, "/dev/stdin";}		# If no file specifies, use STDIN
   my $mbox = shift;
   foreach (read_mbox $mbox) {
	my $message;
	%attachments = ();
	my $match=0;
	my $parser = new MIME::Parser;
	# Create and set the output directory:
	$parser->output_dir("/tmp");
	$parser->output_prefix("part");
	$parser->output_to_core("NONE");
	my $mail = Mail::Internet->new($_);

	my $body = $mail->body;
	my $head = $mail->head;

	# Find attachments and save them
	my @lines = (@{$mail->header}, "\n", @{$mail->body});
	my $entity = $parser->parse_data(\@lines);
	&process_attachments($entity);

   }

# Determine what attachments should be saved
sub process_attachments {
	my $entity = shift;
	&get_attachments($entity);
	foreach my $file (sort keys %attachments) {
			print "$file\n";
			unlink("$file"); #uncomment if you want to save the attachment
	}
}

# Create a hash of the attachments in the entity - recursively gathers them since they can be multipart
sub get_attachments {
	my ($entity, $name) = @_;
	defined($name) or $name = "'anonymous'";

	my @parts = $entity->parts;
	if (@parts) {
		my $i;
		foreach $i (0 .. $#parts) {
			get_attachments($parts[$i], ("$name, part ".(1+$i)));
		}
	}
	else {
		my $type = $entity->head->mime_type;
		my $body = $entity->bodyhandle;
		my $path = $body->path;
		$attachments{$path} = $type if $path;
	}
	
}

