├── LICENSE
├── README.md
└── email_bot.py
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Kamil Kuczera
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # email-automation-with-gpt-ai-and-python
2 | An example of using the OpenAI API in python to automate email responses
3 |
4 | 1. This script was created to automatically reply to emails in an email inbox using OpenAI API.
5 | The script allows you to reply to only unread messages or to all messages in the inbox.
6 | Sent messages are moved to the specified folder.
7 |
8 | 2. The program is ready to use. You only need:
9 | a.) Install the OpenAI library:
10 | ```sh
11 | pip install openai
12 | ```
13 | b.) Complete the API key and login details
14 |
15 |
16 |
17 | 4. If you find a bug or have an idea to improve the program, please e-mail me.
18 |
19 |
--------------------------------------------------------------------------------
/email_bot.py:
--------------------------------------------------------------------------------
1 | import smtplib, ssl
2 | import time
3 | import imaplib
4 | import email
5 | import openai
6 | from email.mime.multipart import MIMEMultipart
7 | from email.mime.text import MIMEText
8 |
9 |
10 | class mail_bot:
11 | def __init__(self, api_key, api_role, sender, mail_host, password, sender_email, sent_folder, inbox_folder, IMAP_SSL, SMTP_SSL):
12 | self.api_key = api_key
13 | self.api_role = api_role
14 | self.sender = sender
15 | self.mail_host = mail_host
16 | self.password = password
17 | self.sender_email = sender_email
18 | self.sent_folder = sent_folder
19 | self.inbox_folder = inbox_folder
20 | self.IMAP_SSL = IMAP_SSL
21 | self.SMTP_SSL = SMTP_SSL
22 |
23 | def reply_to_emails(self, unread_messages: bool):
24 | # Unread mails
25 | unread_mails = [[], [], [], []]
26 |
27 | # Connect to the mailbox
28 | mail = imaplib.IMAP4_SSL(self.mail_host)
29 | mail.login(self.sender_email, self.password)
30 | mail.select(self.inbox_folder)
31 |
32 | # Search for unread emails in the mailbox
33 | status, messages = mail.search(None, 'UNSEEN' if unread_messages else 'ALL')
34 | message_ids = messages[0].split()
35 |
36 | for msg_id in message_ids:
37 | # Fetch the email
38 | status, data = mail.fetch(msg_id, '(RFC822)')
39 | raw_email = data[0][1]
40 | email_message = email.message_from_bytes(raw_email)
41 |
42 | # Extract email details
43 | sender = email_message['From']
44 | subject = email_message['Subject']
45 | date = email_message['Date']
46 |
47 | #Get the email body content
48 | body = self.get_email_body(email_message)
49 |
50 | # Generate answer with gpt
51 | new_body = mail_operator.ai_responder(body)
52 |
53 | # Send email
54 | mail_operator.send_email(subject=subject, body=new_body, receiver_email=sender)
55 |
56 | mail.logout()
57 | return unread_mails
58 |
59 | def get_email_body(self, email_message):
60 | body = ""
61 |
62 | if email_message.is_multipart():
63 | for part in email_message.walk():
64 | content = part.get_content_type()
65 | disposition = str(part.get('Content-Disposition'))
66 | if content == 'text/plain' and 'attachment' not in disposition:
67 | body = part.get_payload(decode=True)
68 | break
69 | else:
70 | body = email_message.get_payload(decode=True)
71 |
72 | return body
73 |
74 | def send_email(self, subject, body, receiver_email):
75 |
76 | # Create a multipart message and set headers
77 | message = MIMEMultipart()
78 | message["From"] = self.sender_email
79 | message["To"] = receiver_email
80 | message["Subject"] = subject
81 |
82 | # Add body to email
83 | message.attach(MIMEText(str(body), "plain"))
84 |
85 | # Add attachment to message and convert message to string
86 | text = message.as_string()
87 |
88 | # Log in to server using secure context and send email
89 | context = ssl.create_default_context()
90 | with smtplib.SMTP_SSL(self.mail_host, self.SMTP_SSL, context=context) as server:
91 | server.login(self.sender_email, self.password)
92 | server.sendmail(self.sender_email, receiver_email, text)
93 |
94 | # Add email to send folder, and mark email as seen
95 | imap = imaplib.IMAP4_SSL(self.mail_host, self.IMAP_SSL)
96 | imap.login(self.sender_email, self.password)
97 | imap.append(self.sent_folder, '\\Seen', imaplib.Time2Internaldate(time.time()), text.encode('utf8'))
98 | imap.logout()
99 |
100 | def ai_responder(self, message):
101 |
102 | openai.api_key = self.api_key
103 | response = openai.ChatCompletion.create(
104 | model="gpt-3.5-turbo-0301",
105 | messages=[
106 | {
107 | "role": "system",
108 | "content": self.api_role
109 | },
110 | {
111 | "role": "user",
112 | "content": str(message)
113 | }
114 | ],
115 | temperature=0.8,
116 | max_tokens=256
117 | )
118 |
119 | # Return generated message
120 | my_openai_obj = list(response.choices)[0]
121 | return (my_openai_obj.to_dict()['message']['content'])
122 |
123 |
124 | if __name__ == "__main__":
125 |
126 | # Private Variables (replace this with your data)
127 | new_api_key = "Your api key"
128 | new_mail_host = "Your mail host"
129 | new_password = "Your e-mail password"
130 | new_your_email = "Your e-mail address"
131 |
132 | # GPT variables
133 | new_api_role = "You are a service assistant. You try to solve problems."
134 |
135 | # Email Variables
136 | new_subject = "generated answer with GPT BOT"
137 | new_sender = "GPT BOT"
138 | new_sent_folder = 'SENT'
139 | new_inbox_folder = 'INBOX'
140 | new_SMTP_SSL = 465
141 | new_IMAP_SSL = 993
142 |
143 |
144 | # Instance of bot class
145 | mail_operator = mail_bot(
146 | new_api_key,
147 | new_api_role,
148 | new_sender,
149 | new_mail_host,
150 | new_password,
151 | new_your_email,
152 | new_sent_folder,
153 | new_inbox_folder,
154 | new_IMAP_SSL,
155 | new_SMTP_SSL
156 | )
157 |
158 | # Here we read all messages
159 | unread_messages = mail_operator.reply_to_emails(unread_messages=True)
160 |
161 | print("done")
162 |
--------------------------------------------------------------------------------