Skip to content

Instantly share code, notes, and snippets.

@jfierstein
Created April 22, 2019 05:01
Show Gist options
  • Save jfierstein/d9722d28c31c383262bdb1b1df228177 to your computer and use it in GitHub Desktop.
Save jfierstein/d9722d28c31c383262bdb1b1df228177 to your computer and use it in GitHub Desktop.
Python script for scraping Gmail inbox for Amazon package emails with today as delivery date (written for Home Assistant)
import sys, smtplib, time
import datetime
import imaplib
import email
import json
EMAIL = "<YOURADDRESS>@gmail.com"
PWD = "<YOURSECRETPASSWORD>"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT = 993
deliveriesToday = []
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(EMAIL,PWD)
mail.select('INBOX')
today = datetime.date.today()
def check_amazon(param):
try:
past_date = datetime.date.today() - datetime.timedelta(days=3)
tfmt = past_date.strftime('%d-%b-%Y')
type, sdata = mail.search(None, '(FROM "amazon.com" SINCE ' + tfmt + ')')
mail_ids = sdata[0]
id_list = mail_ids.split()
for i in id_list:
typ, data = mail.fetch(i, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1])
email_subject = msg['subject']
email_from = msg['from']
email_msg = str(msg.get_payload(0))
today_month = datetime.date.today().month
today_day = datetime.date.today().day
if "will arrive:" in email_msg:
start = email_msg.find("will arrive:") + len("will arrive:")
end = email_msg.find("Track your package:")
arrive_date = email_msg[start:end].strip()
arrive_date = arrive_date.split(" ")
arrive_date = arrive_date[0:3]
arrive_date[2] = arrive_date[2][:2]
arrive_date = " ".join(arrive_date).strip()
dateobj = datetime.datetime.strptime(arrive_date, '%A, %B %d')
if dateobj.day == datetime.date.today().day and dateobj.month == datetime.date.today().month:
subj_parts = email_subject.split('"')
if len(subj_parts) > 1:
deliveriesToday.append(subj_parts[1])
else:
deliveriesToday.append("Amazon Order")
if param == "count":
print(json.dumps(len(deliveriesToday)))
else:
print(json.dumps(deliveriesToday))
except:
print("Unexpected error:", sys.exc_info()[0])
raise
if __name__ == "__main__":
param = sys.argv[1]
if param == "count":
check_amazon("count")
else:
check_amazon("items")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment