· 7 years ago · Oct 16, 2018, 06:10 AM
1#!/usr/bin/env python
2
3import re
4import smtplib
5import time
6import imaplib
7import email
8import sqlite3
9import datetime
10
11ORG_EMAIL = "@gmail.com"
12FROM_EMAIL = "keap.todo" + ORG_EMAIL
13FROM_PWD = "TODO"
14SMTP_SERVER = "imap.gmail.com"
15SMTP_PORT = 993
16
17
18def clean_email(email):
19 return [i for i in re.split(r'[\r\n]', email) if i != '']
20
21def get_new_email():
22 try:
23 mail = imaplib.IMAP4_SSL(SMTP_SERVER)
24 mail.login(FROM_EMAIL,FROM_PWD)
25 mail.select('inbox')
26 typ, data = mail.search(None, '(UNSEEN)')
27
28 if typ == 'OK':
29 for num in data[0].split():
30 if num == '':
31 print 'No new emails !'
32 continue
33
34 ret, message = mail.fetch(num,'(RFC822)')
35 for messages in message:
36 if isinstance(messages, tuple):
37 fetched_records = dict()
38 mess = messages[1].decode('utf-8')
39 original = email.message_from_string(mess)
40 date = email.utils.parsedate_tz(original.get('date'))
41 if date:
42 local_date = datetime.datetime.fromtimestamp(
43 email.utils.mktime_tz(date)
44 )
45 else:
46 print 'Not able to parse date'
47 break
48 if 'put' or 'get' in original.get('subject'):
49 fetched_records['subject'] = original.get('subject')
50 fetched_records['from'] = original.get('from')
51 fetched_records['data'] = {'day': local_date.day, 'month': local_date.month, 'year': local_date.year}
52
53 for part in original.walk():
54 if part.get_content_type() == "text/plain":
55 body = part.get_payload(decode=True)
56 fetched_records['msg'] = clean_email(body)
57
58 if 'put' in original.get('subject'):
59 # store in db
60 #q = clean_email(fetched_records.get('msg'))
61 pass
62 else:
63 # get from db
64 #q = parse_email(fetched_records.get('msg'))
65 pass
66 print fetched_records
67 else:
68 print typ
69
70 except Exception as e:
71 print e
72
73get_new_email()