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

Hi. I would like to extract attachment from email and save it to disk (it's a popular issue, isn't it?). I've tried to use Mail::POP3Client and MIME::Parser as follows
#!/usr/bin/perl use strict; use warnings; use Mail::POP3Client; use MIME::Parser; my $pop = new Mail::POP3Client( USER => 'login', PASSWORD => 'password', HOST => 'server', USESSL => 1 ); my $fh = new IO::Handle(); my $parser = new MIME::Parser; for (my $i = 1; $i <= $pop->Count(); $i++) { open (OUT, ">msg-$i.msg"); $fh->fdopen( fileno(OUT), "w" ); $pop->HeadAndBodyToFile( $fh, $i ); close OUT; my $entity = $parser->parse_open("msg-$i.msg"); } $pop->close();
and found it doesn't work correctly. At the first glance it works properly but attachment saves corrupted. For example, I send JPEG and after download and parse the mail I can view saved JPEG in standard browsers but picture looks cropped. In my mind MIME::Parser loses some data when parse saved mail... I can't solve this problem for some days and I'm really frustrated :(

Replies are listed 'Best First'.
Re: extract attachment from email again
by Anonymous Monk on Feb 27, 2012 at 16:24 UTC
    You opened the file in text mode, but you want to save binary data, so you have to open it in raw mode instead. Binary data written in text mode "cooks" the newlines.
    use autodie qw(:all); . . . for my $i (1 .. $pop->Count) { open my $fh, '>:raw', "msg-$i.msg"; $pop->HeadAndBodyToFile($fh, $i); close $fh; }
      It works. Thanks a lot.