Home:ALL Converter>Perl - Decoding a pdf attached to an email in MIMO Base64 yields to an empty pdf

Perl - Decoding a pdf attached to an email in MIMO Base64 yields to an empty pdf

Ask Time:2018-06-08T22:03:36         Author:nck

Json Formatter

I'm trying to do the following:

  1. Login to my email provider.
  2. Download the last email which shall have a pdf attachment.
  3. Decode de pdf and save it to a file.

My problem: When I open the pdf (Adobe reader, IE, foxit reader...) it opens as an empty sheet.

If I open the file with a text editor and compare it with the same file that I downloaded manually using a webclient the only difference is a new line in the middle of the file. Missing line

Even if I remove that new line I still become an empty sheet. And both files have exactly the same content and both are opened as ANSI in the text editor.

This is the code I have used so far:

use strict;
use warnings;
#use utf8;
#use open ':std', ':encoding(UTF-8)';
#binmode(STDOUT, ":utf8");

use Mail::IMAPClient;
use MIME::Base64;

my $imap = Mail::IMAPClient->new(
    Server   => 'myprovider',
    User     => 'myuser',
    Password => 'mypassword',
    Port     => '993',
    Ssl      => 1,
    Uid      => 1,
) or die "Cannot connect: $@";


# Select folder
$imap->select( 'INBOX' ) or die "Select folder error: ", $imap->LastError, "\n";

# Get all messages
my $messages = $imap->messages;

# Read whole message
my $message = $imap->message_string(@$messages[-1]);
print "\n\n\n\nWhole message: \n\n\n$message\n";

# Read message
my $part_body = $imap->bodypart_string(
    @$messages[-1],
    '1.1',
) or die "Could not get bodypart string: ", $imap->LastError;
print "Email content:\n$part_body\n";

# Read attachment
my $pdf_attachment = $imap->bodypart_string(
    @$messages[-1],
    '2.1',
) or die "Could not get bodypart string: ", $imap->LastError;
$pdf_attachment =~ s/-/+/g;
$pdf_attachment =~ s/_/\//g;
my $decoded_attachment = decode_base64($pdf_attachment);


# Logout
$imap->logout or die "Logout error: ", $imap->LastError, "\n";

# Save attachment
open(my $fh, '>', 'mypdf.pdf');
print $fh $decoded_attachment;
close $fh;
print "done\n";

# Save email
open($fh, '>', 'email.txt');
print $fh $message;
close $fh;
print "done\n";

PD: The email source code looks like this:

--=_4e399e1756412414214821321834

Content-Type: application/octet-stream

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename="my_file-2018-06-08.pdf"



JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL01lZGlh

Qm94IFEuODkwXQovVHJpbUJveCBbMCDAgNTk1LjI4MCA4ND4wMDAgMC4wMDAgNTk1LjI4MCA4

...

Author:nck,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50762413/perl-decoding-a-pdf-attached-to-an-email-in-mimo-base64-yields-to-an-empty-pdf
yy