-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
245 lines (189 loc) · 8.23 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import imaplib
import email
from email.header import decode_header
import re
# Your email and app password
username = "[email protected]"
password = "kklg hkou kcbo rrvd"
def clean_text(text):
# Remove unwanted characters and decode
return "".join(filter(lambda x: x.isprintable(), text))
def extract_feedback(email_body):
# Regex to find feedback or relevant keywords
feedback_pattern = re.compile(r"(feedback|review|suggestion|comment)", re.IGNORECASE)
if feedback_pattern.search(email_body):
return email_body.strip() # Clean and return the feedback
return "No feedback found."
def get_emails():
# Connect to the Gmail IMAP server
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# Login to the account
imap.login(username, password)
# Select the mailbox you want to extract emails from
imap.select("inbox")
# Search for all emails
status, messages = imap.search(None, "ALL")
email_ids = messages[0].split()
# Process the latest email
latest_email_id = email_ids[-1]
# Fetch the email by ID
res, msg = imap.fetch(latest_email_id, "(RFC822)")
for response_part in msg:
if isinstance(response_part, tuple):
# Parse the email content
msg = email.message_from_bytes(response_part[1])
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
# Decode the subject if it's in bytes
subject = subject.decode(encoding if encoding else "utf-8")
# Extract the email sender
from_ = msg.get("From")
# If the email message is multipart
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
# Get the body of the email
if "attachment" not in content_disposition:
if content_type == "text/plain":
email_body = part.get_payload(decode=True).decode()
# Clean the email body and extract feedback
cleaned_body = clean_text(email_body)
feedback = extract_feedback(cleaned_body)
print(f"Subject: {subject}")
print(f"From: {from_}")
print(f"Feedback Extracted: {feedback}")
else:
# If not multipart, process plain text email
content_type = msg.get_content_type()
if content_type == "text/plain":
email_body = msg.get_payload(decode=True).decode()
cleaned_body = clean_text(email_body)
feedback = extract_feedback(cleaned_body)
print(f"Subject: {subject}")
print(f"From: {from_}")
print(f"Feedback Extracted: {feedback}")
# Close the connection and logout
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import imaplib
import email
from email.header import decode_header
from datetime import datetime
from textblob import TextBlob # Import TextBlob for sentiment analysis
import re
from concurrent.futures import ThreadPoolExecutor
# Your email and app password
username = "[email protected]"
password = "kqbv nxgy bgok fovc"
# Compile feedback pattern once (cached)
feedback_pattern = re.compile(r"(feedback|review|suggestion|comment|jayanthidress|dress)", re.IGNORECASE)
def clean_text(text):
return "".join(filter(lambda x: x.isprintable(), text))
def extract_feedback(email_body):
if feedback_pattern.search(email_body):
return email_body.strip() # Clean and return the feedback
return None # Return None if no feedback is found
def format_email_date(email_date):
# Parse the date into a datetime object
date_obj = email.utils.parsedate_to_datetime(email_date)
# Format the date into dd/mm/yyyy
return date_obj.strftime("%d/%m/%Y")
def decode_payload(part):
try:
payload = part.get_payload(decode=True)
if isinstance(payload, bytes):
for encoding in ['utf-8', 'ISO-8859-1', 'latin1']:
try:
return payload.decode(encoding)
except UnicodeDecodeError:
continue
return str(payload)
except Exception as e:
return ""
def analyze_sentiment(feedback):
# Analyze feedback sentiment using TextBlob
analysis = TextBlob(feedback)
polarity = analysis.sentiment.polarity # Get polarity score: -1 (negative) to +1 (positive)
if polarity > 0:
return "Positive"
elif polarity < 0:
return "Negative"
else:
return "Neutral"
def process_email(email_data):
# Parse the email content
msg = email.message_from_bytes(email_data)
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
subject = subject.decode(encoding if encoding else "utf-8")
from_ = msg.get("From")
date_ = msg.get("Date")
# If the email message is multipart
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
# Get the body of the email
if "attachment" not in content_disposition and content_type == "text/plain":
email_body = decode_payload(part)
cleaned_body = clean_text(email_body)
feedback = extract_feedback(cleaned_body)
if feedback: # Only process if feedback is found
formatted_date = format_email_date(date_)
sentiment = analyze_sentiment(feedback) # Perform sentiment analysis
print(f"From: {from_}")
print(f"Subject: {subject}")
print(f"Date: {formatted_date}")
print(f"Feedback Extracted: {feedback}")
print(f"Sentiment: {sentiment}\n")
else:
# If the email isn't multipart (simple plain text)
email_body = decode_payload(msg)
cleaned_body = clean_text(email_body)
feedback = extract_feedback(cleaned_body)
if feedback: # Only process if feedback is found
formatted_date = format_email_date(date_)
sentiment = analyze_sentiment(feedback) # Perform sentiment analysis
print(f"From: {from_}")
print(f"Subject: {subject}")
print(f"Date: {formatted_date}")
print(f"Feedback Extracted: {feedback}")
print(f"Sentiment: {sentiment}\n")
def get_unread_emails():
# Connect to Gmail's IMAP server
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# Login to the account
imap.login(username, password)
# Select the mailbox you want to read (inbox)
imap.select("inbox")
# Search for all unread emails
status, messages = imap.search(None, "UNSEEN")
# Get the list of email IDs (unread emails)
email_ids = messages[0].split()
if not email_ids:
print("No new emails found.")
return
# Decode email IDs from bytes to strings
email_ids = [email_id.decode() for email_id in email_ids]
# Process emails in batches (fetch all in one go)
max_emails_to_fetch = 50 # Adjust as necessary
email_ids = email_ids[:max_emails_to_fetch]
# Fetch all emails in a single request
res, msgs = imap.fetch(",".join(email_ids), "(RFC822)")
# Each response from the fetch can contain multiple parts, so loop through each one
for i in range(0, len(msgs), 2):
response = msgs[i]
if isinstance(response, tuple):
email_data = response[1]
process_email(email_data) # Process each email individually
# Mark the emails as read by adding the \Seen flag to all processed emails
imap.store(",".join(email_ids), '+FLAGS', '\Seen')
# Close the connection and logout
imap.close()
imap.logout()
if __name__ == "__main__":
get_unread_emails()
imap.close()
imap.logout()
if __name__ == "__main__":
get_emails()