I am reading email from an IMAP server using the
Mail::IMAPClient
module over SSL.
I am able to extract the body of the email but not the attachment.
Please suggest how can I download the email attachment? I want to avoid downloading attachment inside the attachments. i.e. multilevel attachments.
Here is how I am fetching the email body
my $struct = $client->get_bodystructure( $msg_id );
if ( $struct->bodytype ne "MULTIPART" ) {
print "\n BodyEnc:" . $struct->bodyenc();
}
my $rDecode = decode( $struct, $client, $msg_id );
if ( $rDecode ne "" && ( length( $rDecode ) > 2 ) ) {
print( $rDecode . "\n" );
}
foreach my $dumpme ( $struct->bodystructure() ) {
if ( $dumpme->bodytype() eq "MULTIPART" ) {
next;
}
$rDecode = "";
$rDecode = decode( $dumpme, $client, $msg_id );
if ( ( $rDecode ne "" ) && ( length( $rDecode ) > 2 ) ) {
print( $rDecode . "\n" );
}
}
sub decode {
my ( $process, $imap, $msg_id ) = @_;
if ( $process->bodytype eq "TEXT" ) {
if ( $process->bodyenc eq "base64" ) {
return decode_base64( $imap->bodypart_string( $msg_id, $process->id ) );
}
elsif ( index( " -7bit- -8bit- -quoted-printable- ", lc( $process->bodyenc ) ) != -1 ) {
return $imap->bodypart_string( $msg_id, $process->id );
}
}
Finally I was able to download the email attachment. I just needed to create a new file with the same extension as the attached file in the email and write the content to it by decoding the attachment content.