Skip to content

Instantly share code, notes, and snippets.

@umrashrf
Last active February 18, 2019 13:48
Show Gist options
  • Save umrashrf/1dbc7ceffae3f24482f51eaffd810ab0 to your computer and use it in GitHub Desktop.
Save umrashrf/1dbc7ceffae3f24482f51eaffd810ab0 to your computer and use it in GitHub Desktop.
Download emails from GMail API and extract files from each email using Python and GYB
import os
import sys
import email
for line in sys.stdin:
fle = line.strip()
if str.lower(fle[-3:]) == "eml":
msg = email.message_from_file(open(fle))
attachments = msg.get_payload()
for attachment in attachments:
try:
fnam = attachment.get_filename()
fnam = os.path.split(fle)[0] + '/' + fnam
with open(fnam, 'wb') as f:
f.write(attachment.get_payload(decode=True,))
except Exception as detail:
pass
GYB-GMail-Backup/2015/8/17/14f3c3e2c5ba5a4f.eml
GYB-GMail-Backup/2015/8/17/14f3b4c111382a0f.eml
GYB-GMail-Backup/2015/8/10/14f172d29a344670.eml
GYB-GMail-Backup/2015/8/10/14f1734143eb77f7.eml
GYB-GMail-Backup/2015/8/24/14f5f4adfaed419b.eml
GYB-GMail-Backup/2015/8/24/14f5f50237ef0b98.eml
GYB-GMail-Backup/2015/8/31/14f82f0ef337fce8.eml
GYB-GMail-Backup/2015/8/31/14f8405d01b9dd0a.eml
GYB-GMail-Backup/2015/8/3/14ef2dd2ad483fb8.eml
GYB-GMail-Backup/2015/8/3/14ef2e23459fe68d.eml
GYB-GMail-Backup/2015/4/6/14c8e7f8ac03a4c0.eml
GYB-GMail-Backup/2015/4/6/14c8e7e124fab2d3.eml
@umrashrf
Copy link
Author

umrashrf commented Feb 19, 2017

$ cat files_with_attachments.txt | python3 extract_attachments.py

@umrashrf
Copy link
Author

$ gyb --email [email protected] --search "from:[email protected]"
$ grep -l -R "Content-Type: application/octet-stream" GYB-GMail-Backup/ | tee files_with_attachments.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment