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

Hello Perl Monks, I have to write a code, where i have to login to the inbox of a user and from the mail in the inbox, i have to extract the attachment from the mail to a location. I have written the below piece of code.
my $pop = Net::POP3->new($server); die "\nCouldn't connect to the server.\n\n" unless $pop; my $num_messages = $pop->login($receiveruname,$password);
from here i do not know how to get access to the mail and extract the attachment from the mail. Please help me with this since i am badly stuck at this point. Thanks, Nisha

2005-11-17 Retitled by Arunbear, as per Monastery guidelines
Original title: 'Net::pop3'

Replies are listed 'Best First'.
Re: Extracting attachments from mails with Net::POP3
by borisz (Canon) on Nov 17, 2005 at 08:31 UTC
    Untested. Save attachments to $attachment_dir.
    use Carp; use Email::MIME; use File::Basename; use Net::POP3; my $server = '...'; my $receiveruname = '...'; my $password = '...'; my $attachment_dir = '/tmp'; my $pop = Net::POP3->new($server); croak "Couldn't connect to the server.\n\n" unless $pop; my $num_messages = $pop->login( $receiveruname, $password ); croak "Connection trouble network password user ..." unless defined $num_messages; for my $i ( 1 .. $num_messages ) { my $aref = $pop->get($i); my $em = Email::MIME->new( join '', @$aref ); for ( my @parts = $em->parts ) { print $_->content_type, "\n"; next unless $_->content_type =~ m(^application/octet-stream)i; my $filename = basename( $_->filename || '' ); my $basefilename = $filename || 'UNNAMED'; my $cnt = 0; while ( -e "$attachment_dir/$filename" ) { my ( $d, $m, $y ) = (localtime)[ 3 .. 5 ]; $filename = sprintf( "%s_%04d%02d%02d_%04d", $basefilename, $y + 1900, $m + 1, $d, ++$cn +t ); } open my $fh, ">", "$attachment_dir/$filename" or croak $!; binmode $fh; print $fh $_->body; $pop->delete($i); } } $pop->quit;
    Boris
      Thank You very much!!!!
Re: Extracting attachments from mails with Net::POP3
by Corion (Patriarch) on Nov 17, 2005 at 07:34 UTC

    The code you have so far bears no relation to your problem. With the Net::POP3 module, you can retrieve the mail from your server. You then need to parse out the attachments.

    I recommend you first retrieve the mail into a local file for easier debugging and then write a program to parse attachments from the locally saved mail. MIME::Parser is a convenient module to parse the parts of a mail message, and the Mail and Email namespaces hold other MIME parsing modules.