Python Tricks to Automate Email Responses Using ChatGPT

Automate Email Responses Using ChatGPT

Ajay Parmar
The Pythoneers
8 min readJul 13, 2024

--

Photo by RDNE Stock project

What kind of works would you like to be done through ChatGPT?

Yeah, I know your dirty mind started wandering for what thing.

No, no, no… obviously, it cannot prepare your morning breakfast and night dinner or your favorite dish and all.

It has its own limitations; it’s just an AI language model that generates text, audio, video, and images based on given prompts.

But let’s get practical. As sarcastic engineers with creative minds, we always find solutions to our problems.

So here in this insightful blog, we prepare ChatGPT for your most useful automated email response work.

In our busy schedules, many of us face hectic workloads where it becomes crucial to efficiently manage internet communications and emails. By leveraging ChatGPT, you can streamline your email responses, saving you valuable time and reducing stress.

Stay tuned as we dive into the specifics of how to set-up and use ChatGPT for automating your email responses, making your life a bit easier amidst the chaos.

but before let’s understand first some basic terminologies.

Chat GTP:

ChatGPT is an advanced AI language model developed by OpenAI. It generates human-like text based on input, using deep learning and the transformer architecture. Trained on diverse internet text, ChatGPT can answer questions, draft emails, write code, and more. It understands context but doesn’t have real-time knowledge or access to personal data unless shared in the conversation.

AI Language Module:

An AI language model like ChatGPT generates human-like text using deep learning and transformer architecture. Trained on vast datasets, it learns language patterns and context. When given input, it processes the text through neural networks to generate relevant responses. Using attention mechanisms, it focuses on important parts of the input for contextually appropriate output. It doesn’t have real-time knowledge or personal data access, responding based on training data patterns.

Python:

Python is a versatile high-level programming language known for its readability and simplicity. It supports multiple programming paradigms and is widely used in web development, scientific computing, data analysis, artificial intelligence, and more. Python’s extensive standard library and active community contribute to its popularity, making it suitable for beginners and experts alike.

How you can done Automate Email Responses Using ChatGP

screenshot

Interesting blog, interesting idea. Here are the steps for how this is going to happen

This given Python code is designed to help you manage your emails more efficiently by using a smart computer program called ChatGPT to read and reply to your messages automatically. Here’s how it works:

First, you need to set up some special tools or libraries that the script will use to read emails, send emails, and use ChatGPT.

These tools are like apps that help the script do its job.

Next, the script connects to your email account. It logs in using your email address and password, just like you do when you open your email app or website.

The Code then looks for specific types of emails, specifically those with the subject “Delivery Status Notification.” These emails usually mean that something went wrong when you tried to send a message to someone.

Once it finds these emails, the script reads them to understand what went wrong.

It extracts important details from the email like who sent it, what the subject is, and the main message. The script handles different formats of emails to make sure it can read them correctly.

After reading the email, the script asks ChatGPT for help. ChatGPT is a smart computer program that can read and understand text. The script sends the main message of the email to ChatGPT, which then writes a helpful reply.

Finally, the script takes the reply written by ChatGPT and sends it back to the person who sent the original email. It logs into your email again, composes a new email with the reply, and sends it.

This process saves you time because you don’t have to read and reply to each email yourself. Instead, the script does it for you using smart replies generated by ChatGPT. This makes your email responses more efficient and allows you to focus on other important tasks.

1. Setup Dependencies

Ensure you have necessary Python modules installed: (required application)

```bash
pip install imaplib email smtplib openai
```

2. Implementing the Enhanced Automation Script:

Here, we use simple Python code to generate automated email reply to banna shop for their failed delivery 5 dozen bananas as an example.

```python
import imaplib
import email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from openai import ChatCompletion, ChatGPT
# Initialize ChatGPT instance
chatgpt = ChatGPT(api_key='your_openai_api_key')
# Function to fetch and process emails
def fetch_and_process_emails():
# Connect to your email server
mail = imaplib.IMAP4_SSL('imap.yourmailserver.com')
mail.login('your_email@example.com', 'your_password')
mail.select('inbox')

# Search for emails with delivery failure notifications
_, data = mail.search(None, '(UNSEEN SUBJECT "Delivery Status Notification")')

for num in data[0].split():
_, msg = mail.fetch(num, '(RFC822)')
raw_email = msg[0][1]
email_message = email.message_from_bytes(raw_email)

# Extract relevant details from the email
sender = email_message['From']
subject = email_message['Subject']
body = ""

if email_message.is_multipart():
for part in email_message.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
if ctype == 'text/plain' and 'attachment' not in cdispo:
body = part.get_payload(decode=True)
break
else:
body = email_message.get_payload(decode=True)

# Generate response using ChatGPT
response_text = generate_response(body)

# Send response email
send_response(sender, subject, response_text)

mail.close()
mail.logout()
# Function to generate response using ChatGPT
def generate_response(prompt):
completion = chatgpt.complete(prompt, max_tokens=50)
return completion.choices[0].text.strip()
# Function to send response
def send_response(receiver, subject, response_text):
# Construct email message
msg = MIMEMultipart()
msg['From'] = 'your_email@example.com'
msg['To'] = receiver
msg['Subject'] = f"Re: {subject}"
msg.attach(MIMEText(response_text, 'plain'))
# Connect to SMTP server and send email
server = smtplib.SMTP('smtp.yourmailserver.com', 587)
server.starttls()
server.login('your_email@example.com', 'your_password')
text = msg.as_string()
server.sendmail('your_email@example.com', receiver, text)
server.quit()
# Main function to run the script
def main():
fetch_and_process_emails()
if __name__ == "__main__":
main()
```

Explanation:

Dependencies: We import `openai` along with other standard modules (`imaplib`, `email`, `smtplib`, `MIMEMultipart`, `MIMEText`) to handle email processing, SMTP communication, and ChatGPT integration.

`chatgpt` Initialization:
Initialize `chatgpt` with your OpenAI API key to utilize ChatGPT for generating automated responses.

Enhanced `generate_response` Function:
Uses `chatgpt.complete` method to generate a response based on the email content (`prompt`). Adjust `max_tokens` and other parameters as needed for your use case.

Integration with `fetch_and_process_emails` Function:
Instead of a simple fail code, `generate_response` now generates a response text using ChatGPT based on the email content.
This response text is then sent as the email reply (`send_response` function).

Up to now, this has all been about the Python code — how it will execute and the whole process. But it’s all about implementation after you have an application built for this specific purpose. So, our next topic is about what to do with that Python code.

What to Do with the Provided Python Code?

Photo by Pixabay:

This given code is designed to be implemented within a Python application or script. When designing a specific application, make sure the application is ready by yourself.

Inserting the email automation Python code into your application involves several crucial steps to ensure seamless functionality and reliability.

First, you need to consider the overall design of your application and how this automation feature will fit into its existing architecture.

This could mean integrating it with current functionalities or designing it as a standalone module dedicated to managing email responses.

Here’s a breakdown of how you can integrate it into an application:

Steps to Integrate the Code into an Application:

  1. Install Required Packages:
    Ensure you have the necessary Python packages installed using the following command:
```bash
pip install imaplib email smtplib openai
```

2. Create a Python Script:
Copy the provided Python script into a `.py` file, for example, `email_autoresponder.py`.

3. Modify Script with Your Details:
Replace placeholders like `’your_openai_api_key’`, `’imap.yourmailserver.com’`, `’your_email@example.com’`, and `’your_password’` with your actual API key, IMAP server details, email address, and password.

4. Set Up Your Environment:
Ensure your environment has access to the necessary libraries and credentials. You may consider using environment variables for sensitive information like API keys and passwords.

5. Run the Script:
Execute the script by running it with Python:

```bash
python email_autoresponder.py
```

This will start the process of fetching emails, generating responses using ChatGPT, and sending replies via SMTP.

final output:

The final output is a Python application that automates email responses using ChatGPT. The Code connects to your email server, searches for unseen emails with the subject “Delivery Status Notification,” and processes each email to extract relevant details such as the sender, subject, and body.

Here’s the final output integrated with the specific example of handling a failed delivery of five dozen bananas:

Output Execution start from here:

Incoming Email:
Subject: Delivery Status Notification: Failed Delivery

Body:

```
Dear Customer,
We regret to inform you that your order of 5 dozen bananas could not be delivered due to unforeseen circumstances. We apologize for the inconvenience and will keep you updated on the status of your order.
Best regards,
Delivery Service Team
```

Generated Response:
Subject: Re: Delivery Status Notification: Failed Delivery

Body:

```
Dear Delivery Service Team,
Thank you for informing me about the failed delivery of my order of 5 dozen bananas. I understand that unforeseen circumstances can arise. Please keep me updated on the status of my order and let me know if there is anything I can do to assist in resolving this issue promptly.
Best regards,
[Your Name]
```

Learning Outcomes

By the end of this guide, you will:

1. Understand the basics of ChatGPT and how it can be used for automating tasks.
2. Learn to set up the Python environment for email automation.
3. Access and read emails using Python.
4. Generate automated email responses with ChatGPT.
5. Send automated responses via email.
6. Integrate and schedule the automation script for efficient email management.

Conclusion:

In conclusion, integrating Python scripts for email automation using ChatGPT can significantly streamline your email management processes. By setting up and customizing the provided Python code, you can automate responses to specific email notifications efficiently. This process involves connecting to your email server, extracting necessary details from incoming emails, generating responses using AI, and sending replies automatically. Once integrated into your application, this tool can save time and enhance productivity, ensuring consistent and timely communication. Stay tuned for our next article, which will guide you on what to do with the Python code and how to build an application around it.

Final Message :

Thank you for following along on how to automate email responses using ChatGPT with Python. This automation can streamline your email management and ensure timely responses.

Stay tuned for our next article on building a specific application around this code.

Until next time, happy coding! 👨‍💻💖

Check out my other data-related articles on Medium. If you enjoy my content, let’s connect over a virtual coffee break. Thank you for your support!

--

--

Ajay Parmar
The Pythoneers

Artificial Intelligence | Data Science | Tech Enthusiast | Python | ML | | Cyber | SQL | Founder of NewZolokiya