You are parsing data incorrectly (try long lines or lines starting with "--" to get a bunch of email-control characters.
Use Mail::Message to get attachments out of the email and manipulate mime types better.
use Mail::Message;
my $fromline = <STDIN>;
my $msg = Mail::Message->read(\*STDIN);
if($msg->isMultipart) {
for($msg->body->parts) {
open(my $tofile,">/tmp/filename")
or die "Error opening tmpfile: $!";
$_->print($tofile);
close $tofile;
# print
}
}
As you might guess, multiple attachments are also handled correctly.