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

Greetings Great Minds!

I'm creating a script that will read the incoming mail, get the attachments and save
each of those attachments along with the content in a seperate files.
The following snippet gets the attachments and dumps the contents in a single file. This not what I need.
If the incoming mail has three attachments, then the script should create three files for each of the attachment(s) along with the content.

The attachments may contain images/text and may be of type text/html.
Can anyone let me know how to achieve that.
#!/usr/bin/perl use MIME::Parser; use Data::Dumper; parse_email(); sub parse_email { my $dir = "/tmp/attachments"; my $parser = new MIME::Parser; $parser->output_dir($dir); my $entity = $parser->read(\*STDIN) || die "couldn't parse MIME stre +am"; my $head = $entity->head; my $content = $head->as_string . "\n"; my @parts = $entity->parts; my $body = $entity->bodyhandle; $content .= $body->as_string if defined $body; my $part; for $part (@parts) { my $path = ($part->bodyhandle) ? $part->bodyhandle->path : undef; } return $content; }

Replies are listed 'Best First'.
Re: Saving all email attachments into various files.
by brian_d_foy (Abbot) on Jan 09, 2005 at 07:28 UTC

    MIME::Parser can do all of that for you. It's parse() method will automatically break apart the message and save the bits in separate files.

    #!/usr/bin/perl use MIME::Parser; my $p = MIME::Parser->new; $p->output_dir( "/Users/brian/Desktop" ); $p->parse( \*STDIN );

    If you want the whole message, read it and store it in a variable then use the parse_data() method instead.

    I have a full program in my "Detaching attachments" article in the September 2004 issue of The Perl Journal.

    --
    brian d foy <bdfoy@cpan.org>
      Brian,

      Thanks for your suggestion. I'm going to use parse_data() method and will try to break the attachments.

      Currently I don't have the September issue of TPJ
      .
Re: Saving all email attachments into various files.
by trammell (Priest) on Jan 08, 2005 at 18:25 UTC
    I'm not sure what OS you use, but you may have a utility already available (e.g. munpack) that meets your needs.
      I use Linux for all purposes (Dev/Testing). I've looked at "munpack".
      Looks like its only for Windows.
        I have munpack on various GNU/Linux machines. In the Debian distribution it's part of the mpack package.
Re: Saving all email attachments into various files.
by fuzzyping (Chaplain) on Jan 08, 2005 at 20:46 UTC