Perl - 将附加到MIMO Base64中的电子邮件的pdf解码为空pdf

时间:2018-06-08 14:03:37

标签: perl base64 decode

我正在尝试执行以下操作:

  1. 登录我的电子邮件提供商。
  2. 下载最后一封带有pdf附件的电子邮件。
  3. 解码de pdf并将其保存到文件中。
  4. 我的问题: 当我打开pdf(Adobe阅读器,IE,foxit阅读器......)时,它会以空白页打开。

    如果我使用文本编辑器打开文件并将其与我使用webclient手动下载的同一文件进行比较,唯一的区别是文件中间的新行。 Missing line

    即使我删除了新行,我仍然会变成空白页。这两个文件具有完全相同的内容,并且都在文本编辑器中以ANSI的形式打开。

    这是我到目前为止使用的代码:

    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:电子邮件源代码如下所示:

    --=_4e399e1756412414214821321834
    
    Content-Type: application/octet-stream
    
    Content-Transfer-Encoding: base64
    
    Content-Disposition: attachment; filename="my_file-2018-06-08.pdf"
    
    
    
    JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL01lZGlh
    
    Qm94IFEuODkwXQovVHJpbUJveCBbMCDAgNTk1LjI4MCA4ND4wMDAgMC4wMDAgNTk1LjI4MCA4
    
    ...
    

1 个答案:

答案 0 :(得分:0)

我刚发现问题,我需要使用binmode来保存文件:

open(OUTFILE,">>mypdf.pdf"); 
binmode OUTFILE;
print OUTFILE $decoded_attachment;
close(OUTFILE);