0

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. enter image description here

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 = "[email protected]"
    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, "[email protected]", msg)
                    server.quit()
                else:
                    print("no email");

            else:
                continue

1 Answer 1

1

Solution 1: Doing checks on the same line

if ("Emergency" in subject) and ("Alert" in email_message):
   ***your logic goes here***

Solution 2: Using Modularized checks

def subject_check(subject):
   if "Emergency" in subject:
       ***logic**
   elif <some_check> :
       ***logic***
   else:
       ***logic***

Create separate functions for other checks, so that you can reuse the check logic somewhere else too.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the respond, actually what I'm doing is letting user to entered their own value or condition to be parse. So I couldn't estimate what is the exact value of the parameter that they want to filter. If you're interested you can look at my prefer question. Here
I posted my answer to that question too, please check it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.