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

Hi, I'm trying to parse information out of the body of what I believe is a base64 encoded email:
Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64
I'm mostly a perl novice. I'm trying to use MIME::Parser, which I believe is the best module for doing this. I've read practically every google response on how to use this module that exists, and still don't understand how to get the decoded version of the body.

The decoded message is written to disk by default, but I don't understand how to store the decoded body in an array so I can manipulate it.

http://www.perlmonks.org/bare/?node_id=188084

I've even followed this extensive example, and it also doesn't appear to decode the body.

A short, simple example would be most appreciated.

I've written the following bit of code, but it doesn't appear to go into the for-loop:

#!/usr/bin/perl -w use strict; use MIME::Parser; my $tmp_dir = '/tmp/parser-dir'; my $parser = MIME::Parser->new; mkpath($tmp_dir) unless -d $tmp_dir; $parser = MIME::Parser->new( ); $parser->extract_uuencode(1); $parser->extract_nested_messages(1); my $entry = $parser->parse(\*STDIN); for my $part ($entry->parts) { # dig into the parts if($part->mime_type eq 'multipart/alternative') { for my $a ($part->parts) { if($a->mime_type eq 'text/plain') { $part = $a; last; } } } my $mime = $part->mime_type; if($mime =~ m'text/.+' && !$found_msg++) { my $fh = $part->open('r'); if($fh) { while(defined(my $line = $fh->getline)) { $line =~ s/[\r\n]//g; push(@message, $line); } $fh->close; } } }

Replies are listed 'Best First'.
Re: Need help parsing email using MIME::Parser
by Anonymous Monk on Mar 31, 2015 at 22:25 UTC

    The decoded message is written to disk by default, but I don't understand how to store the decoded body in an array so I can manipulate it.

    Read the file? Yeah, read the file sounds good :)

      I figured it out. I knew it seemed stupid to not have some method of reading the unencoded file directly using the $entity that's already defined and accessing the full email.

      I just came across this:

      ### Read the (unencoded) body data: if ($io = $ent->open("r")) { while (defined($_ = $io->getline)) { print $_ } $io->close; }
      Yes, thanks, of course I knew that, but isn't it possible to read from the file since it's already opened?

        Yes, thanks, of course I knew that, but isn't it possible to read from the file since it's already opened?

        Um, what file are you talking about?

        Use mimeexplode to unpack an email into a directory

        Then use any which way or Path::Tiny to read the files that got unpacked, they're like regular files at this point, not emails