I have different parameter and condition to be filter before executing a function.
For example: An email subject must contain Emergency
and does not contain hehe
. In the meantime, the text of the same email must contain alert
and do not contain haha
to execute a function.
Currently I'm just using a hard-coded if else
to filter the request, but it can only process a single rules. What I want to achieve is all the rules will be parse before executing a function.
My Py script (This script is just checking if the Email subject have "Consent" in it)
import datetime
import email
import imaplib
import mailbox
import smtplib
while True:
EMAIL_ACCOUNT = "xxx@gmail.com"
PASSWORD = "xxx"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(EMAIL_ACCOUNT, PASSWORD)
mail.list()
mail.select('inbox')
result, data = mail.uid('search', None, "UNSEEN") # (ALL/UNSEEN)
i = len(data[0].split())
for x in range(i):
latest_email_uid = data[0].split()[x]
result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
# result, email_data = conn.store(num,'-FLAGS','\\Seen')
# this might work to set flag to seen, if it doesn't already
raw_email = email_data[0][1]
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# Header Details
date_tuple = email.utils.parsedate_tz(email_message['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
local_message_date = "%s" % (str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))
email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))
email_to = str(email.header.make_header(email.header.decode_header(email_message['To'])))
subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))
# Body details
for part in email_message.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
print("From:", email_from)
print("Email To:", email_to)
print("date:", local_message_date)
print("Subject:", subject)
print("body:", body.decode('utf-8'))
'''If subject have "Consent" it will send specific email to recipient'''
if "Consent" in subject:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(EMAIL_ACCOUNT, PASSWORD)
msg = "ALERT NOTICE!"
server.sendmail(EMAIL_ACCOUNT, "xxx@gmail.com", msg)
server.quit()
else:
print("no email");
else:
continue
Aucun commentaire:
Enregistrer un commentaire