1

I have a python script that will be triggered to read an inbox and send email to an gmail account when some condition is meet. In order to send , the script will filter through subject or text of the incoming email. Currently the script is just hard-coded format and I prefer the condition is dynamically set by the user. I created a django website and let user to input their condition, but I do not know how can I pass the parameter from the web to my python script. I already do my researched on the internet but couldn't found any useful source, does anyone can help me or send my any related article for me to read ? Thanks

My py script

import datetime
import email
import imaplib
import mailbox
import smtplib

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 test 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

My django web currently is just html form My django web interface

Html

<!DOCTYPE html>
<html lang="en">
<html>
<head>
    <link href="https://fonts.googleapis.com/css?family=Quicksand:300,500" rel="stylesheet">

<style>

body {font-family: 'Quicksand', sans-serif;}
.button {
  border-radius: 50px;
  background-color:  #ff9633;
  border: none;
  color: #FFFFFF;
  text-align: center;
  font-size: 15px;
  padding: 10px;
  width: 80px;
  transition: all 0.5s;
  cursor: pointer;
  margin: 5px;
  margin-left:500px;
}

.button span {
  cursor: pointer;
  display: inline-block;
  position: relative;
  transition: 0.5s;
}

.button span:after {
  content: '\00bb';
  position: absolute;
  opacity: 0;
  top: 0;
  right: -20px;
  transition: 0.5s;
}

.button:hover span {
  padding-right: 25px;
}

.button:hover span:after {
  opacity: 1;
  right: 0;
}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  width: 45%;

  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.4s
}


/* Add Animation */
@-webkit-keyframes animatetop {
  from {top:-300px; opacity:0}
  to {top:0; opacity:1}
}

@keyframes animatetop {
  from {top:-300px; opacity:0}
  to {top:0; opacity:1}
}

/* The Close Button */
.close {
  color: white;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

.modal-header {
  padding: 2px 16px;
  background-color: #ff9633;
  color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
  padding: 2px 16px;
  background-color: #ff9633;
  color: white;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #ff9633;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  background-color:
#fa7d34;
}
</style>
</head>
<body>

<ul>

  <li><div id="myBtn1"><a href="#AddCon">Alert Policies</a></div></li>
  <li><a href="#contact">Test3</a></li>
  <li><a href="#about">Test4</a></li>
</ul>

<!-- The Modal -->
<div id="myModal" class="modal">
  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Alert Policies</h2>
    </div>
    <div class="modal-body">

        <p style="font-size:14px">Please select an event parameter as well as the condition type and value that apply.</p>

        <!-- parameter drop down -->
        <form action="/action_page.php">
            <label for="Parameter"> <b style="font-size:13px" >  Event parameter to evaluate </b></label>
            <select name="Parameter" id="Parameter" style="width:340px; font-family: 'Quicksand', sans-serif;">
                <option disabled selected value>select a parameter</option>
                <option value="Subject">Subject</option>
                <option value="Text">Text</option>

            </select>
            <br><br>

            <label for="Condition">   <b style="font-size:13px" >  Type of condition </b></label>
            <select name="Condition" id="Condition" style="width:340px; margin-left:69px; font-family: 'Quicksand', sans-serif;">
                <option disabled selected value>select a condition</option>
                <option value="Equals">Equals</option>
                <option value="Contain">Contain</option>
                <option value="NotContain">Does not contain</option>

            </select>
            <br><br>

            <label for="valuetomatch"> <b style="font-size:13px" > Value to match</b></label>
            <input type="text" id="valuetomatch" name="valuetomatch" style="width:333px; margin-left:80px; font-family: 'Quicksand', sans-serif;">
            <br>
            <br>
<button class="button"><span>OK</span></button>

  </form>

    </div>


  </div>

</div>

<script>
// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn1");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>

</body>
</html>
2
  • Can you please share the codes regarding I created a django website and let user to input their condition? Commented May 11, 2021 at 6:33
  • I just created the html form, its just front end. I do not know how to make it pass parameter. I updated my html form above. thanks Commented May 11, 2021 at 6:43

1 Answer 1

1

If your condition data is serializable, then you can use Celery to run python script. It'll be as simple as:

# in your Django code that run on user submitting data
...
send_email.delay()
...

# Celery task
@shared_task(bind=True)
def send_email(list_of_your_condition_parameters):
    # do job
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I will try this to see if it work or not

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.