Skip to content

Instantly share code, notes, and snippets.

@disjustin
Last active May 30, 2024 18:38
Show Gist options
  • Select an option

  • Save disjustin/0caa1befa2794d1000d4a96bb9af3169 to your computer and use it in GitHub Desktop.

Select an option

Save disjustin/0caa1befa2794d1000d4a96bb9af3169 to your computer and use it in GitHub Desktop.
# Download attachments from unread Outlook emails from a specified date
'''
#requirements.txt
pypiwin32==223
pywin32==306
'''
# Download attachments from unread Outlook emails from a specified date
# original: https://www.linkedin.com/pulse/using-python-download-outlook-excel-attachment-victor-sun/
import os
import sys
from win32com.client import Dispatch
import datetime
import pathlib
# https://stackoverflow.com/a/1094933/14875035
# bytes -> human readable file size
def sizeof_fmt(num, format="natural", suffix="B"):
if format == "binary":
for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"
else:
for unit in ("", "k", "M", "G", "T", "P", "E", "Z"):
if abs(num) < 1000.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1000.0
return f"{num:.1f}Y{suffix}"
# Save specific email attachments from Outlook
def save_attachments(messages, date, path):
for message in messages:
# only check if email is unread and from specified date
if message.Unread or message.Senton.date() == date:
attachments = message.Attachments
for attachment in attachments:
# only check if attachment is excel
if pathlib.Path(str(attachment.Filename)).suffix == ".xlsx":
print(f"Download: {attachment.Filename} from {message.Subject} on {message.SentOn} with the file size: {sizeof_fmt(attachment.Size,'')}")
attachment.SaveAsFile(os.path.join(path, str(attachment)))
print(f"Download Complete: {os.path.join(path, str(attachment))}")
else:
print(f"Skip: {attachment.Filename}")
break
def main():
print(sys.argv)
if len(sys.argv) >= 2:
path = sys.argv[1]
else:
path = os.getcwd()
parse_date = datetime.date.today()
# Use GetNameSpace ("MAPI") to return the Outlook NameSpace object from the Application object.
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
# https://stackoverflow.com/a/48179963/14875035
#6 = Inbox (without mails from the subfolder)
inbox = outlook.GetDefaultFolder(6)
subFolder = inbox.Folders("Automated Reports")
# "Automated Reports" is the specific subfolder within the "Inbox"
messages = subFolder.Items
save_attachments(messages, parse_date, path)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment