I am trying to pull a PDF file out of a gmail message via IMAP, and write it to file on local disk.

I can successfully connect to gmail, search (and find) the message in question, grab it in its entirety as a string, and navigate to the attachment. Now I need to decode it, and write it to file. Here is that portion of my code:

my $str = $client->message_string($id) or die "$0: message_string: $@" +; Email::MIME->new($str)->walk_parts(sub { my($part) = @_; #Skip non-attachment parts return unless $part->content_type =~ /\bname="([^"]+)"/; #Keep the filename from the MIME info my $name = "$1"; #No spaces in file names we're writing. $name =~ s/ /_/g; print "Writing $name...\n"; #Open the file for writing open my $fh, ">", $name or die "$0: open $name: $!"; my $blob = $part->body_raw; my $cleanPDF = decode_base64($blob); print $fh "$cleanPDF"; close $fh or warn "$0: close $name: $!"; });

This writes a file, and it opens as a PDF. However, it's 3 blank pages.

Even more frustrating, if I just print '$blob' as a txt file, and copy the contents, I can use an online base64 decoder like this one: http://www.opinionatedgeek.com/dotnet/tools/base64decode/

And the resultant file opens as a PDF and has my content.

Any reason that decode_base64() is not returning a readable file? The file it does write is very close in size, (402KB vs 398KB for a good file), and kdiff reports that they're ascii-identical, but not binary-identical. All the readable parts match. I'm on Windows, using Perl 5.10.1 and MIME::Base64 version 3.13.


In reply to decode_base64 MIME PDF Failing by kiteskitesyay

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.