Link to home
Start Free TrialLog in
Avatar of shodgkiss
shodgkiss

asked on

Decode email message

Hi,

I have written a Perl program to retrieve email messages the only problem is decoding the message. I simply want the Body of the message, any attachments and the header values in a hash.

Thanks in advance,
Steve
Avatar of andreif
andreif
Flag of Canada image

Hi,
here is a solution
------------------

use MIME::Parser;

$parser = new MIME::Parser;
$parser->output_dir("/tmp");

$entity = $parser->read(\*STDIN) or die "Couldn't parse MIME stream";

------------------

After that you can use    
$entity->head - for message header
$entity->bodyhandle - for message body
$entity->parts - for parts of multipart message (attachments)

Check manuals for
MIME::Parser
There are nice examples

Avatar of shodgkiss
shodgkiss

ASKER

andreif,

Before i give you the points could you give me an example of placing the attachments to a file on the server?

Thanks a lot
Steve
oh and i have the message in a variable on the server called $message, how do you use that instead of STDIN??
Hi Shodgkiss,

use

$entity = $parser->parse_data($message);

to parse data from variable

All attached files will stored in the directory, specified with
$parser->output_dir("/tmp");

(in my example /tmp, of course)
 
you can see the structure of the entity using
print $entity->dump_skeleton;

to see attached files use array $entity->parts
every entry is also an entity. The entity object has useful methods like

$entity->mime_type
$entity->path

Check documentation for MIME::Entity module for the full list of properties
So, your code can be like this

use MIME::Parser;

$parser = new MIME::Parser;
$parser->output_dir("/tmp");

$entity = $parser->parse_data($message);

# do something with $entity->head; $entity->bodyhandle

foreach $ent ($entity->parts) {
  # do something with $ent->path; $ent->bodyhandle;
}

ASKER CERTIFIED SOLUTION
Avatar of andreif
andreif
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial