|
| 1 | +import ezgmail |
| 2 | + |
| 3 | +def attachmentdownload(resulthreads): |
| 4 | + # Two Objects used in code are GmailThread and GmailMessage |
| 5 | + # 1. GmailThread - Represents conversation threads |
| 6 | + # 2. GmailMessage - Represents individual emails within Threads |
| 7 | + countofresults = len(resulthreads) |
| 8 | + try: |
| 9 | + for i in range(countofresults): |
| 10 | + if len(resulthreads[i].messages) > 1: # checks whether the count of messages in threads is greater than 1 |
| 11 | + for j in range(len(resulthreads[i].messages)): |
| 12 | + resulthreads[i].messages[ |
| 13 | + j].downloadAllAttachments() # downloads attachment(s) for individual messages |
| 14 | + else: |
| 15 | + resulthreads[i].messages[0].downloadAllAttachments() # downloads attachment(s) for single message |
| 16 | + print("Download compelete. Please check your root directory.") |
| 17 | + except: |
| 18 | + raise Exception("Error occured while downloading attachment(s).") |
| 19 | + |
| 20 | + |
| 21 | +if __name__ == '__main__': |
| 22 | + query = input("Enter search query: ") |
| 23 | + newquery = query + " + has:attachment" # appending to make sure the result threads always has an attachment |
| 24 | + resulthreads = ezgmail.search(newquery) # search functions accepts all the operators described at https://support.google.com/mail/answer/7190?hl=en |
| 25 | + |
| 26 | + if len(resulthreads) == 0: |
| 27 | + print("Result has no attachments:") # Executed if results don't have attachment |
| 28 | + else: |
| 29 | + print("Result(s) with attachments:") |
| 30 | + for threads in resulthreads: |
| 31 | + print(f"Email Subject: {threads.messages[0].subject}") # prints the subject line of email thread in results |
| 32 | + try: |
| 33 | + ask = input( |
| 34 | + "Do you want to download attachment(s) in result(s) (Yes/No)? ") # Allows user to decide whether they want to download attachment(s) or not |
| 35 | + if ask == "Yes": |
| 36 | + attachmentdownload(resulthreads) # calls the function that downloads attachment(s) |
| 37 | + else: |
| 38 | + print("Program exited") |
| 39 | + except: |
| 40 | + print("Something went wrong") |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | + |
0 commit comments