Skip to content

Instantly share code, notes, and snippets.

@MaizerGomes
Forked from x011/gmail_attachment_downloader.py
Last active January 15, 2021 16:07
Show Gist options
  • Select an option

  • Save MaizerGomes/4229c5ff614d89c6a58b3971df1afb9b to your computer and use it in GitHub Desktop.

Select an option

Save MaizerGomes/4229c5ff614d89c6a58b3971df1afb9b to your computer and use it in GitHub Desktop.
Gmail Attachment Downloader 2020
from imap_tools import MailBox, AND # pip3 install imap_tools
import traceback
from datetime import datetime
from sys import exit
import os
host = "imap.gmail.com"
username = ""
password = ''
download_folder = "/home/maizerg/Downloads/sigeup"
valid_senders = []
if not os.path.isdir(download_folder):
os.makedirs(download_folder, exist_ok=True)
mail = MailBox(host)
mail.login(username, password)
messages = mail.fetch(AND(seen=False), mark_seen=False)
messages_count = 0
print(datetime.now())
for message in messages:
if message.from_ in valid_senders:
for idx, attachment in enumerate(message.attachments):
try:
att_fn = attachment.filename
if attachment.content_type in ['text/plain', 'application/octet-stream']:
download_path = f"{download_folder}/{att_fn}"
print("Found new file:", download_path)
with open(download_path, "wb") as fp:
fp.write(attachment.payload)
mail.seen([message.uid], True)
except:
pass
print(traceback.print_exc())
else:
mail.seen([message.uid], True)
print("Email ignored from:", message.from_)
messages_count += 1
mail.logout()
print(messages_count, "Emails processed!")
print("Connection Closed.")
print("______________________________________________")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment