Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am attempting to parse attachment file names from e-mail messages. Here is a test script I am working on that doesn't quite work (it uses a test e-mail message saved to a text file):
use Mail::Field; use MIME::Head; use strict; my $file="c:/batch/perl/temp2_file.txt"; my $testhead = MIME::Head->from_file("$file"); my $name = $testhead->get("Content_Disposition.filename"); my $mime_type=$testhead->mime_type; my $mime_encoding=$testhead->mime_encoding; my $boundary=$testhead->multipart_boundary; print "MIME TYPE = $mime_type\n"; print "MIME ENCODING = $mime_encoding\n"; print "BOUNDARY = $boundary\n"; print "FILE NAME = $name\n";
Here is the output it produces:
MIME TYPE = multipart/mixed
MIME ENCODING = 7bit
BOUNDARY = BlatBoundary-V3HaOfXtBB3MDNzDt14bu
FILE NAME =

As you can see, I am not able to get the attachment file name of test.scr. What am I doing wrong? Is there an easier way to go about this?

Below is the test e-mail message I have been using:

Date: Sun, 24 Aug 2003 18:46:49 -0500
From: postmaster@somewhere.com
Subject: this is a test mail with attachment
To: me@somewhere.com
MIME-Version: 1.0
Content-Type: Multipart/Mixed; boundary="BlatBoundary-V3HaOfXtBB3MDNzDt14bu"
X-Mailer: WinNT's Blat ver 1.9.4 http://www.blat.net
--BlatBoundary-V3HaOfXtBB3MDNzDt14bu
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7BIT
Content-description: Mail message body
Some junk text here.
5898wvBd2-734Brkh7774xdaV7-657Al29
--BlatBoundary-V3HaOfXtBB3MDNzDt14bu
Content-Type: application/octet-stream; name=test.scr
Content-Disposition: attachment; filename="test.scr"
Content-Transfer-Encoding: BASE64
YXNkZg0KYXNkZg0KYXNkZg0KYXNkZg0K
--BlatBoundary-V3HaOfXtBB3MDNzDt14bu--

Replies are listed 'Best First'.
Re: Parse attachment file names from e-mail
by sgifford (Prior) on Aug 25, 2003 at 19:11 UTC

    Everything after the blank line (not shown, but probably before "Some junk text here.") is the body of the message, not the headers. The body may contain further MIME parts, each of which has its own headers, but you'll have to look at each one seperately.

    I believe you'll want to use MIME::Parser to parse the message. It will give you a MIME::Entity which will have a parts() method that should give you all of the MIME parts. Each of these parts will have a MIME::Head object (accessible through the head() method) with the headers for that part.

    Be aware that each MIME part can itself contain nested parts.