jeremyephron / simplegmail

A simple Gmail API client for applications in Python
MIT License
336 stars 73 forks source link

Download only one type of files (PDF) #79

Open mabusdogma opened 2 years ago

mabusdogma commented 2 years ago

Your scripts are great! I wonder how to dowload ony one type of attachments, for example PDFs or Excel files.

mabusdogma commented 2 years ago

Nevermind, I got it! This is an example to download only Excel files, from unread emails, 7 or less days old:

from simplegmail import Gmail
from simplegmail.query import construct_query

gmail = Gmail()
query_params = {
    "newer_than": (7, "day"),
    "unread": True,
    "spec_attachment":'xlsx', #PDF or whatever you want
}

messages = gmail.get_messages(query=construct_query(query_params))

try:
 message = messages[0]
 if message.attachments:
    for attm in message.attachments:
        print('File: ' + attm.filename)
        attm.save()  # downloads and saves each attachment under it's stored
                     # filename. You can download without saving with `attm.download()`
except:
 print("Error, probably no specified files found")
 exit()