NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

from flask import Flask, request, jsonify
import imaplib
import email
import requests
import ipdb
import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
import json
import schedule
import time
from threading import Thread

app = Flask(__name__)
app.debug = True

# API endpoint URLs
CONFIG_ENDPOINT = "https://imap.gmail.com/config"
ANSWER_ENDPOINT = "https://api.example.com/answer"

# Authentication token
TOKEN = "your_access_token"

MOVE_TO_VETTED_DELAY = 2 # Seconds to wait before moving email to vetted folder
ALERT_DELAY = 10 # Seconds to wait before creating an alert/notification

REPLY_DELAY = 10 # Seconds to wait before replying to the sender

@app.route('/static_response', methods=['GET'])
def static_response():
response = {
"skye_handled": True,
"reply": "AI generated reply",
"classifier": ["keyword 1", "keyword 2"]
}
return jsonify(response)

@app.route('/process_emails', methods=['POST'])
def process_emails():
with app.app_context():
try:
# Parse request data
request_data = request.json
email_account = request_data.get("email_account")
imap_host = request_data.get("imap_host")
imap_user = request_data.get("imap_user")
imap_password = request_data.get("imap_password")
imap_port = int(request_data.get("imap_port"))

mail = imaplib.IMAP4_SSL(imap_host)
mail.login(imap_user, imap_password)
mail.select("INBOX")

# Search for all unseen emails
result, data = mail.search(None, 'UNSEEN')
if result == 'OK':
message_numbers_bytes = data[0] if data else b''
message_numbers_str = message_numbers_bytes.decode('utf-8')
message_numbers_list = message_numbers_str.split()

emails = []
processed_email_ids = []

for email_id in message_numbers_list:
result, data = mail.fetch(email_id, '(RFC822)')
raw_email = data[0][1]
msg = email.message_from_bytes(raw_email)
body = get_email_body(msg)

# Move email to "vetted" folder after x1 seconds
time.sleep(MOVE_TO_VETTED_DELAY)
mail.copy(email_id, 'vetted')
mail.store(email_id, '+FLAGS', 'Deleted')

# Create alert/notification after x2 seconds
thread = Thread(target=create_alert, args=(email_id,))
thread.start()

# Reply to the sender after x3 seconds
time.sleep(REPLY_DELAY)

# Call static_response endpoint to get the response
static_response_data = requests.get(f"{request.host_url}static_response").json()

add_custom_headers(msg, static_response_data['classifier'])
email_data = {
'from': msg['From'],
'subject': msg['Subject'],
'body': body,
'sender': msg['From']
}

# Add classification tags from the response to the email body
if static_response_data['classifier']:
for tag in static_response_data['classifier']:
email_data['body'] += f"n[{tag}]"

emails.append(email_data)
processed_email_ids.append(email_id)

# Move email to "processed" folder if skye_handled is True
if static_response_data['skye_handled']:
mail.copy(email_id, 'processed')
mail.store(email_id, '+FLAGS', 'Deleted')

send_acknowledgment_email(email_account, email_data['sender'], email_data['body'], email_data['subject'], "tag1")

if processed_email_ids:
mail.expunge()

mail.logout()

return jsonify(emails)
else:
return jsonify({"error": "Error in search: {}".format(result)}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500

def create_alert(email_id):
time.sleep(ALERT_DELAY - MOVE_TO_VETTED_DELAY)
print(f"Alert created for email {email_id}")

# Helper functions
def get_email_body(msg):
body = ""
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
if content_type == 'text/plain' or content_type == 'text/html':
body += part.get_payload(decode=True).decode(part.get_content_charset(), 'ignore')
else:
charset = msg.get_content_charset() or 'utf-8'
body = msg.get_payload(decode=True).decode(charset, 'ignore')
return body

def add_custom_headers(msg, classification_tags):
for tag in classification_tags:
msg.add_header(tag, 'True')

def send_acknowledgment_email(email_account, sender, body, subject, classification_tags):
# Define SMTP server details
smtp_host = 'smtp.gmail.com' # Update with your SMTP server
smtp_port = 587 # Update with your SMTP port
smtp_user = '[email protected]' # Update with your SMTP username
smtp_password = 'vhgc voac plhp rjjp' # Update with your SMTP password

# Compose acknowledgment email
soup = BeautifulSoup(body, 'html.parser')
prettified_body = soup.prettify()
acknowledgment_msg = MIMEText(prettified_body, 'html')

acknowledgment_msg['From'] = email_account
acknowledgment_msg['To'] = sender
acknowledgment_msg['Subject'] = subject

# Add classification tags as headers
add_custom_headers(acknowledgment_msg, classification_tags)

# Send acknowledgment email
try:
with smtplib.SMTP(smtp_host, smtp_port) as smtp:
smtp.starttls()
smtp.login(smtp_user, smtp_password)
smtp.send_message(acknowledgment_msg)
print(f"Acknowledgment email sent to {sender}")
except Exception as e:
print(f"Error sending acknowledgment email to {sender}: {e}")

if __name__ == '__main__':
# Schedule the process_emails function to run every minute
schedule.every(1).minutes.do(process_emails)

# Run the scheduler in a separate thread
def run_scheduler():
while True:
schedule.run_pending()
time.sleep(1)

scheduler_thread = Thread(target=run_scheduler)
scheduler_thread.start()

# Start the Flask app
app.run(debug=True)
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.