Last active
July 2, 2019 04:00
-
-
Save se1exin/4672436766aa86133de167078f69ea38 to your computer and use it in GitHub Desktop.
Bulk download Xero Payslips from a Gmail Account
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Install (in a virtualenv) ezgmail, and follow the Gmail API setup steps here: https://pypi.org/project/EZGmail/ | |
# Once you have saved your credentials-gmail.json file, run this python script | |
# Your payslips will be saved to the folder 'payslips' inside the current directory. | |
import ezgmail | |
import os | |
TARGET_DIRECTORY = "./payslips" | |
if os.path.isdir(TARGET_DIRECTORY) == False: | |
os.mkdir(TARGET_DIRECTORY) | |
print("Searching for Payslips in inbox " + ezgmail.EMAIL_ADDRESS) | |
total_downloaded = 0 | |
# ezgmail has a default search limit of 25, change to 200 (modify this if you have more emails) | |
threads = ezgmail.search('from:noreply@xero.com', maxResults=200) | |
# Run through the search results and download the PDFs | |
for thread in threads: | |
for message in thread.messages: | |
# Keep a count incase there are multiple attachments in the same email (used in filename generation) | |
count = 0 | |
for attachment in message.attachments: | |
print("Downloading Payslip for " + message.timestamp.strftime("%Y-%m-%d")) | |
# Download the file first, then rename it | |
message.downloadAttachment(attachment, TARGET_DIRECTORY) | |
# Now rename the file to include email and date | |
target_name = ezgmail.EMAIL_ADDRESS + "_" + message.timestamp.strftime("%Y-%m-%d") + "_" + str(count) + "_" + str(attachment) | |
os.rename(TARGET_DIRECTORY + "/" + str(attachment), TARGET_DIRECTORY + "/" + target_name) | |
count += 1 | |
total_downloaded += 1 | |
# All done! List how many we downloaded | |
print("Downloaded " + str(total_downloaded) + " Payslips") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment