Automated Email Responder

 import imaplib

import smtplib

import email

from email.mime.text import MIMEText

import openai


# Gmail Credentials

EMAIL_USER = "your_email@gmail.com"

EMAIL_PASS = "your_app_password"


# OpenAI API Key (Optional)

OPENAI_API_KEY = "your_openai_api_key"

openai.api_key = OPENAI_API_KEY


# Connect to Gmail Inbox

def check_inbox():

    mail = imaplib.IMAP4_SSL("imap.gmail.com")

    mail.login(EMAIL_USER, EMAIL_PASS)

    mail.select("inbox")


    _, messages = mail.search(None, "UNSEEN")

    email_ids = messages[0].split()


    for email_id in email_ids:

        _, msg_data = mail.fetch(email_id, "(RFC822)")

        for response_part in msg_data:

            if isinstance(response_part, tuple):

                msg = email.message_from_bytes(response_part[1])

                sender = msg["From"]

                subject = msg["Subject"]

                body = extract_body(msg)


                print(f"New Email from: {sender}")

                print(f"Subject: {subject}")

                print(f"Body: {body}")


                reply_message = generate_reply(body)

                send_email(sender, reply_message)


    mail.logout()


# Extract Email Body

def extract_body(msg):

    if msg.is_multipart():

        for part in msg.walk():

            if part.get_content_type() == "text/plain":

                return part.get_payload(decode=True).decode()

    return msg.get_payload(decode=True).decode()


# Generate AI-Based Response (Optional)

def generate_reply(user_query):

    prompt = f"Reply professionally to this email: {user_query}"

    response = openai.ChatCompletion.create(

        model="gpt-3.5-turbo",

        messages=[{"role": "system", "content": "You are a professional email assistant."},

                  {"role": "user", "content": prompt}]

    )

    return response["choices"][0]["message"]["content"]


# Send Email Response

def send_email(to_email, message):

    smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465)

    smtp_server.login(EMAIL_USER, EMAIL_PASS)


    msg = MIMEText(message)

    msg["Subject"] = "Re: Your Inquiry"

    msg["From"] = EMAIL_USER

    msg["To"] = to_email


    smtp_server.sendmail(EMAIL_USER, to_email, msg.as_string())

    smtp_server.quit()

    print(f"Auto-reply sent to {to_email}")


# Run the Email Bot

if __name__ == "__main__":

    check_inbox()


No comments: