174 lines
5.3 KiB
Python
174 lines
5.3 KiB
Python
#!/usr/bin/env python3
|
|
#
|
|
# Very basic example of using Python 3 and IMAP to iterate over emails in a
|
|
# gmail folder/label. This code is released into the public domain.
|
|
#
|
|
# This script is example code from this blog post:
|
|
# http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/
|
|
#
|
|
# This is an updated version of the original -- modified to work with Python 3.4.
|
|
#
|
|
import sys
|
|
import imaplib
|
|
import getpass
|
|
import email
|
|
import email.header
|
|
import datetime
|
|
from IPython import embed
|
|
import re
|
|
|
|
EMAIL_ACCOUNT = "bzigr02"
|
|
EMAIL_FOLDER = "INBOX"
|
|
|
|
fields = ["Fist name", "Last name", "e-Mail", "Institution", "Phone", "Country", "City", "ZIP code", "Street",
|
|
"Fees", "Farewell event (Thu 20 Feb)", "Gwinner Award",
|
|
"Food preferences", "LabTour (Fri 21 Feb)", "Messages"]
|
|
|
|
reg_fees = {'early': {"proMember": 95, "proNonMember":115, "studentMember": 55, "studentNonMember": 65},
|
|
'late': {"proMember": 115, "proNonMember":135, "studentMember": 65, "studentNonMember": 75}}
|
|
|
|
|
|
class Participation(object):
|
|
|
|
def __init__(self, email_message):
|
|
self._registration_date = ""
|
|
self._first_name = ""
|
|
self._last_name = ""
|
|
self._phone = ""
|
|
self._email = ""
|
|
self._student = False
|
|
self._member = False
|
|
self._farewell = False
|
|
self._food_vegi = False
|
|
self._food_vegan = False
|
|
self._food_gluten = False
|
|
self._food_normal = True
|
|
self._address_street = ""
|
|
self._address_city = ""
|
|
self._address_zip = ""
|
|
self._country = ""
|
|
self._institution = ""
|
|
self._fee = 0.0
|
|
|
|
self.__parse_message(email_message)
|
|
|
|
def __parse_message(self, message):
|
|
self._registration_date = message["Date"]
|
|
|
|
msg_body = message.get_payload()[0].as_string()
|
|
msg_body = re.sub(r'=20', ' ', msg_body)
|
|
msg_body = re.sub(r'=\n', '', msg_body)
|
|
msg_body = re.sub(r'=E2=82=AC', 'EUR', msg_body)
|
|
msg_body = re.sub(r'&', 'and', msg_body)
|
|
|
|
lines = msg_body.split('\n')
|
|
self.__parse_food(lines)
|
|
self.__parse_address(lines)
|
|
embed()
|
|
pass
|
|
|
|
def __parse_address(self, lines):
|
|
street = [s for s in lines if s.lower().startswith("street")]
|
|
self._address_street = street[0]
|
|
city = [s for s in lines if s.lower().startswith("city")]
|
|
self._address_city = city[0]
|
|
plz = [s for s in lines if s.lower().startswith("zip")]
|
|
self._address_zip = plz[0]
|
|
inst = [s for s in lines if s.lower().startswith("institution")]
|
|
self._institution = ', '.join(inst)
|
|
|
|
def __parse_food(self, lines):
|
|
food = [l for l in lines if "Food preference" in l]
|
|
if len(food) > 0:
|
|
prefs = food[0].lower()
|
|
self._food_normal = "no special" in prefs
|
|
self._food_vegan = "vegan" in prefs
|
|
self._food_vegi = "vegetarian" in prefs
|
|
self._food_gluten = "gluten" in prefs
|
|
|
|
@property
|
|
def registration_date(self):
|
|
return self._registration_date
|
|
|
|
|
|
def process_mailbox(M):
|
|
"""
|
|
Do something with emails messages in the folder.
|
|
For the sake of this example, print some headers.
|
|
"""
|
|
|
|
rv, data = M.search(None, "UNSEEN")
|
|
if rv != 'OK':
|
|
print("No messages found!")
|
|
return
|
|
|
|
for num in data[0].split():
|
|
rv, data = M.fetch(num, '(RFC822)')
|
|
if rv != 'OK':
|
|
print("ERROR getting message", num)
|
|
return
|
|
|
|
msg = email.message_from_bytes(data[0][1])
|
|
hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
|
|
subject = str(hdr)
|
|
print('Message %s: %s' % (num, subject))
|
|
print('Raw Date:', msg['Date'])
|
|
# Now convert to local date-time
|
|
date_tuple = email.utils.parsedate_tz(msg['Date'])
|
|
if date_tuple:
|
|
local_date = datetime.datetime.fromtimestamp(
|
|
email.utils.mktime_tz(date_tuple))
|
|
print ("Local Date:", \
|
|
local_date.strftime("%a, %d %b %Y %H:%M:%S"))
|
|
|
|
|
|
def process_message(msg_index):
|
|
rv, data = M.fetch(msg_index.encode('ascii'), '(RFC822)')
|
|
if rv != 'OK':
|
|
print("ERROR getting message", rv)
|
|
return
|
|
msg = email.message_from_bytes(data[0][1])
|
|
return Participation(msg)
|
|
|
|
|
|
def process_registrations(M):
|
|
rv, msgs = M.search(None, "SUBJECT", "etho2020", "UNSEEN")
|
|
participations = []
|
|
if rv != "OK":
|
|
print("ERROR searching messages", rv)
|
|
return participations
|
|
|
|
msgs = msgs[0].decode('ascii').split()
|
|
print("Found %i registration mails" % len(msgs))
|
|
for msg_index in msgs:
|
|
participations.append(process_message(msg_index))
|
|
return participations
|
|
|
|
|
|
if __name__ == "__main__":
|
|
M = imaplib.IMAP4_SSL('mailserv.uni-tuebingen.de')
|
|
passwd = "r.8-*0Fc"
|
|
|
|
try:
|
|
rv, data = M.login(EMAIL_ACCOUNT, passwd)
|
|
except imaplib.IMAP4.error:
|
|
print ("LOGIN FAILED!!! ")
|
|
sys.exit(1)
|
|
|
|
#rv, mailboxes = M.list()
|
|
#if rv == 'OK':
|
|
# print("Mailboxes:")
|
|
# print(mailboxes)
|
|
|
|
rv, data = M.select(EMAIL_FOLDER)
|
|
if rv == 'OK':
|
|
print("Processing mailbox %s\n"%EMAIL_FOLDER)
|
|
# process_mailbox(M)
|
|
else:
|
|
print("ERROR: Unable to open mailbox folder ", rv)
|
|
|
|
new_participations = process_registrations(M)
|
|
embed()
|
|
M.close()
|
|
M.logout()
|