Created
October 16, 2018 05:22
-
-
Save prakhar21/d1a80449959a57a12b1823a909331e9a to your computer and use it in GitHub Desktop.
Fetching unseen emails and filtering by subject string
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
#!/usr/bin/env python | |
import re | |
import smtplib | |
import time | |
import imaplib | |
import email | |
import sqlite3 | |
import datetime | |
ORG_EMAIL = "@gmail.com" | |
FROM_EMAIL = "keap.todo" + ORG_EMAIL | |
FROM_PWD = "TODO" | |
SMTP_SERVER = "imap.gmail.com" | |
SMTP_PORT = 993 | |
def clean_email(email): | |
return [i for i in re.split(r'[\r\n]', email) if i != ''] | |
def get_new_email(): | |
try: | |
mail = imaplib.IMAP4_SSL(SMTP_SERVER) | |
mail.login(FROM_EMAIL,FROM_PWD) | |
mail.select('inbox') | |
typ, data = mail.search(None, '(UNSEEN)') | |
if typ == 'OK': | |
for num in data[0].split(): | |
if num == '': | |
print 'No new emails !' | |
continue | |
ret, message = mail.fetch(num,'(RFC822)') | |
for messages in message: | |
if isinstance(messages, tuple): | |
fetched_records = dict() | |
mess = messages[1].decode('utf-8') | |
original = email.message_from_string(mess) | |
date = email.utils.parsedate_tz(original.get('date')) | |
if date: | |
local_date = datetime.datetime.fromtimestamp( | |
email.utils.mktime_tz(date) | |
) | |
else: | |
print 'Not able to parse date' | |
break | |
if 'put' or 'get' in original.get('subject'): | |
fetched_records['subject'] = original.get('subject') | |
fetched_records['from'] = original.get('from') | |
fetched_records['data'] = {'day': local_date.day, 'month': local_date.month, 'year': local_date.year} | |
for part in original.walk(): | |
if part.get_content_type() == "text/plain": | |
body = part.get_payload(decode=True) | |
fetched_records['msg'] = clean_email(body) | |
if 'put' in original.get('subject'): | |
# store in db | |
#q = clean_email(fetched_records.get('msg')) | |
pass | |
else: | |
# get from db | |
#q = parse_email(fetched_records.get('msg')) | |
pass | |
print fetched_records | |
else: | |
print typ | |
except Exception as e: | |
print e | |
get_new_email() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment