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

i have written a script that saves the attachments from all unread messages from a gmail account to my hard drive I am doing this by printing the source code of the attachments into a pdf file created during the scripts run. But all of the PDF files are almost completely corrupt (for some reason 1 in around 20 pages in each file are fine the rest are completely blank) Is there another way to do this or a way to programmatically fix the pdf files I have been at this for days and I i still haven't figured out so any help is appreciated thanks in advance.

use strict; use warnings; # required modules use Net::IMAP::Simple; use Email::MIME; use IO::Socket::SSL; use Email::MIME::Attachment::Stripper; # fill in your details here my $username = 'username@website.com'; my $password = 'password'; my $mailhost = 'imap.gmail.com'; # Connect my $imap = Net::IMAP::Simple->new( $mailhost, port => 993, use_ssl => 1, ) || die "Unable to connect to IMAP: $Net::IMAP::Simple::errstr\n"; # Log in if ( !$imap->login( $username, $password ) ) { print STDERR "Login failed: " . $imap->errstr . "\n"; exit(64); } # Look in the the INBOX my $nm = $imap->select('INBOX'); # How many messages are there? my ($unseen, $recent, $num_messages) = $imap->status(); print "unseen: $unseen, recent: $recent, total: $num_messages\n\n"; my $filepath = "if you want to test it insert own file path here"; ## Iterate through unseen messages for ( my $i = 1 ; $i <= $nm ; $i++ ) { if (!$imap->seen($i) ) { next; } else { my $es = Email::MIME->new( join '', @{ $imap->get($i) } ); #my $es = Email::MIME->new( join '', @{ $imap->top($i) } ); my $text = $es->body; my $stripper = Email::MIME::Attachment::Stripper->new($es); my @attachments = $stripper->attachments; printf( "[%03d] %s\n\t%s\n%s", $i, $es->header('From'), $es->heade +r('Subject'),$text); my $l = 0; foreach $_(@attachments) { my $fh = IO::File->new(); open($fh, '>', "$filepath" . "$_->{filename}"); print $fh "$_->{payload}\n"; $fh->close; } } } # Disconnect $imap->quit; exit;

Replies are listed 'Best First'.
Re: Saving PDF files from gmail
by RonW (Parson) on Jun 25, 2015 at 20:41 UTC

    Maybe this is a line ending issue (especially if running this on non-Linux/Unix systems).

    Try adding ':raw' to the mode in your open call:

    open($fh, '>:raw', "$filepath" . "$_->{filename}");

      thanks but i figured it out and all i was missing was this binmode($fh);

        FYI, adding :raw to the mode in open has the same effect as using binmode
Re: Saving PDF files from gmail
by anonymonk (Acolyte) on Jun 25, 2015 at 17:35 UTC

    for testing purposes I have it so it reads all read messages instead of unread messages in an account so that's why it's like that