Friday, December 5, 2014

Retrieving Gmail blocked attachments




Retrieving Gmail blocked attachments



Sometimes you are unable to download an attachment from Gmail due to the following message:
Anti-virus warning - 1 attachment contains a virus or blocked file. Downloading this attachment is disabled.
Now what ?
 One particular one cought my interest: Show original
Here it is!
Clicking this option opened a text file with the original, MIME encoded message. The interesting thing of course was
------=_NextPart_000_004F_01CA0AED.E63C2A30
Content-Type: application/octet-stream;
      name="phdstuff.rar"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
      filename="phdstuff.rar"

UmFyIRoHAM+QcwAADQAAAAAAAAB0f3TAgCwANAMAAFQEAAACRbXCx8lr9TodMwwAIAAAAG5ld2Zp
bmFsLnR4dA3dEQzM082BF7sB+D3q6QPUNEfwG7vHQgNkiQDTkGvfhOE4mNltIJJlBFMOCQPzPeKD
...
So the whole attachment was contained in that text file, encoded in base64! Now I just needed to extract it from the email and convert it back to binary.
Here’s a simple program that gets an email in text/mime format as input and dumps all attachments:
import email
import sys

if __name__=='__main__':
    if len(sys.argv)<2:
        print "Please enter a file to extract attachments from"
        sys.exit(1)

    msg = email.message_from_file(open(sys.argv[1]))
    for pl in msg.get_payload():
        if pl.get_filename(): # if it is an attachment
            open(pl.get_filename(), 'wb').write(pl.get_payload(decode=True))
Save this to a file named get_attachments.py and, after saving the original message to a file named 0.txt run python get_attachments.py 0.txt and you’ll see the attachments of your email in the same folder!