-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathVCE.py
463 lines (387 loc) · 18.7 KB
/
VCE.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import os
from playsound import playsound
import smtplib
import email
import imaplib
import speech_recognition as sr
from gtts import gTTS
from email.header import decode_header
# import webbrowser
# CONSTANTS
from CONSTANTS import EMAIL_ID, PASSWORD, LANGUAGE
# from CONSTANTS_dev import EMAIL_ID, PASSWORD, LANGUAGE
def SpeakText(command, langinp=LANGUAGE):
"""
Text to Speech using GTTS
Args:
command (str): Text to speak
langinp (str, optional): Output language. Defaults to "en".
"""
if langinp == "": langinp = "en"
tts = gTTS(text=command, lang=langinp)
tts.save("~tempfile01.mp3")
playsound("~tempfile01.mp3")
print(command)
os.remove("~tempfile01.mp3")
def speech_to_text():
"""
Speech to text
Returns:
str: Returns transcripted text
"""
r = sr.Recognizer()
try:
with sr.Microphone() as source2:
r.adjust_for_ambient_noise(source2, duration=0.2)
audio2 = r.listen(source2)
MyText = r.recognize_google(audio2)
print("You said: "+MyText)
return MyText
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
return None
except sr.UnknownValueError:
print("unknown error occured")
return None
def sendMail(sendTo, msg):
"""
To send a mail
Args:
sendTo (list): List of mail targets
msg (str): Message
"""
mail = smtplib.SMTP('smtp.gmail.com', 587) # host and port
# Hostname to send for this command defaults to the FQDN of the local host.
mail.ehlo()
mail.starttls() # security connection
mail.login(EMAIL_ID, PASSWORD) # login part
for person in sendTo:
mail.sendmail(EMAIL_ID, person, msg) # send part
print("Mail sent successfully to " + person)
mail.close()
def composeMail():
"""
Compose and create a Mail
Returns:
None: None
"""
SpeakText("Mention the gmail ID of the persons to whom you want to send a mail. Email IDs should be separated with the word, AND.")
receivers = speech_to_text()
receivers = receivers.replace("at the rate", "@")
emails = receivers.split(" and ")
index = 0
for email in emails:
emails[index] = email.replace(" ", "")
index += 1
SpeakText("The mail will be send to " +
(' and '.join([str(elem) for elem in emails])) + ". Confirm by saying YES or NO.")
confirmMailList = speech_to_text()
if confirmMailList.lower() != "yes":
SpeakText("Operation cancelled by the user")
return None
SpeakText("Say your message")
msg = speech_to_text()
SpeakText("You said " + msg + ". Confirm by saying YES or NO.")
confirmMailBody = speech_to_text()
if confirmMailBody.lower() == "yes":
SpeakText("Message sent")
sendMail(emails, msg)
else:
SpeakText("Operation cancelled by the user")
return None
def getMailBoxStatus():
"""
Get mail counts of all folders in the mailbox
"""
# host and port (ssl security)
M = imaplib.IMAP4_SSL('imap.gmail.com', 993)
M.login(EMAIL_ID, PASSWORD) # login
for i in M.list()[1]:
l = i.decode().split(' "/" ')
if l[1] == '"[Gmail]"':
continue
stat, total = M.select(f'{l[1]}')
l[1] = l[1][1:-1]
messages = int(total[0])
if l[1] == 'INBOX':
SpeakText(l[1] + " has " + str(messages) + " messages.")
else:
SpeakText(l[1].split("/")[-1] + " has " + str(messages) + " messages.")
M.close()
M.logout()
def clean(text):
"""
clean text for creating a folder
"""
return "".join(c if c.isalnum() else "_" for c in text)
def getLatestMails():
"""
Get latest mails from folders in mailbox (Defaults to 3 Inbox mails)
"""
mailBoxTarget = "INBOX"
SpeakText("Choose the folder name to get the latest mails. Say 1 for Inbox. Say 2 for Sent Mailbox. Say 3 for Drafts. Say 4 for important mails. Say 5 for Spam. Say 6 for Starred Mails. Say 7 for Bin.")
cmb = speech_to_text()
if cmb == "1" or cmb.lower() == "one":
mailBoxTarget = "INBOX"
SpeakText("Inbox selected.")
elif cmb == "2" or cmb.lower() == "two" or cmb.lower() == "tu":
mailBoxTarget = '"[Gmail]/Sent Mail"'
SpeakText("Sent Mailbox selected.")
elif cmb == "3" or cmb.lower() == "three":
mailBoxTarget = '"[Gmail]/Drafts"'
SpeakText("Drafts selected.")
elif cmb == "4" or cmb.lower() == "four":
mailBoxTarget = '"[Gmail]/Important"'
SpeakText("Important Mails selected.")
elif cmb == "5" or cmb.lower() == "five":
mailBoxTarget = '"[Gmail]/Spam"'
SpeakText("Spam selected.")
elif cmb == "6" or cmb.lower() == "six":
mailBoxTarget = '"[Gmail]/Starred"'
SpeakText("Starred Mails selected.")
elif cmb == "7" or cmb.lower() == "seven":
mailBoxTarget = '"[Gmail]/Bin"'
SpeakText("Bin selected.")
else:
SpeakText("Wrong choice. Hence, default option Inbox wil be selected.")
imap = imaplib.IMAP4_SSL("imap.gmail.com")
imap.login(EMAIL_ID, PASSWORD)
status, messages = imap.select(mailBoxTarget)
messages = int(messages[0])
if messages == 0:
SpeakText("Selected MailBox is empty.")
return None
elif messages == 1:
N = 1 # number of top emails to fetch
elif messages == 2:
N = 2 # number of top emails to fetch
else:
N = 3 # number of top emails to fetch
msgCount = 1
for i in range(messages, messages-N, -1):
SpeakText(f"Message {msgCount}:")
res, msg = imap.fetch(str(i), "(RFC822)") # fetch the email message by ID
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1]) # parse a bytes email into a message object
subject, encoding = decode_header(msg["Subject"])[0] # decode the email subject
if isinstance(subject, bytes):
subject = subject.decode(encoding) # if it's a bytes, decode to str
From, encoding = decode_header(msg.get("From"))[0] # decode email sender
if isinstance(From, bytes):
From = From.decode(encoding)
SpeakText("Subject: " + subject)
FromArr = From.split()
FromName = " ".join(namechar for namechar in FromArr[0:-1])
SpeakText("From: " + FromName)
SpeakText("Sender mail: " + FromArr[-1])
SpeakText("The mail says or contains the following:")
# MULTIPART
if msg.is_multipart():
for part in msg.walk(): # iterate over email parts
content_type = part.get_content_type() # extract content type of email
content_disposition = str(
part.get("Content-Disposition"))
try:
body = part.get_payload(decode=True).decode() # get the email body
except:
pass
# PLAIN TEXT MAIL
if content_type == "text/plain" and "attachment" not in content_disposition:
SpeakText("Do you want to listen to the text content of the mail ? Please say YES or NO.")
talkMSG1 = speech_to_text()
if "yes" in talkMSG1.lower():
SpeakText("The mail body contains the following:")
SpeakText(body)
else:
SpeakText("You chose NO")
# MAIL WITH ATTACHMENT
elif "attachment" in content_disposition:
SpeakText("The mail contains attachment, the contents of which will be saved in respective folders with it's name similar to that of subject of the mail")
filename = part.get_filename() # download attachment
if filename:
folder_name = clean(subject)
if not os.path.isdir(folder_name):
os.mkdir(folder_name) # make a folder for this email (named after the subject)
filepath = os.path.join(folder_name, filename)
open(filepath, "wb").write(part.get_payload(decode=True)) # download attachment and save it
# NOT MULTIPART
else:
content_type = msg.get_content_type() # extract content type of email
body = msg.get_payload(decode=True).decode() # get the email body
if content_type == "text/plain":
SpeakText("Do you want to listen to the text content of the mail ? Please say YES or NO.")
talkMSG2 = speech_to_text()
if "yes" in talkMSG2.lower():
SpeakText("The mail body contains the following:")
SpeakText(body)
else:
SpeakText("You chose NO")
# HTML CONTENTS
if content_type == "text/html":
SpeakText("The mail contains an HTML part, the contents of which will be saved in respective folders with it's name similar to that of subject of the mail. You can view the html files in any browser, simply by clicking on them.")
# if it's HTML, create a new HTML file
folder_name = clean(subject)
if not os.path.isdir(folder_name):
os.mkdir(folder_name) # make a folder for this email (named after the subject)
filename = "index.html"
filepath = os.path.join(folder_name, filename)
# write the file
open(filepath, "w").write(body)
# webbrowser.open(filepath) # open in the default browser
SpeakText(f"\nEnd of message {msgCount}:")
msgCount += 1
print("="*100)
imap.close()
imap.logout()
def searchMail():
"""
Search mails by subject / author mail ID
Returns:
None: None
"""
M = imaplib.IMAP4_SSL('imap.gmail.com', 993)
M.login(EMAIL_ID, PASSWORD)
mailBoxTarget = "INBOX"
SpeakText("Where do you want to search ? Say 1 for Inbox. Say 2 for Sent Mailbox. Say 3 for Drafts. Say 4 for important mails. Say 5 for Spam. Say 6 for Starred Mails. Say 7 for Bin.")
cmb = speech_to_text()
if cmb == "1" or cmb.lower() == "one":
mailBoxTarget = "INBOX"
SpeakText("Inbox selected.")
elif cmb == "2" or cmb.lower() == "two" or cmb.lower() == "tu":
mailBoxTarget = '"[Gmail]/Sent Mail"'
SpeakText("Sent Mailbox selected.")
elif cmb == "3" or cmb.lower() == "three":
mailBoxTarget = '"[Gmail]/Drafts"'
SpeakText("Drafts selected.")
elif cmb == "4" or cmb.lower() == "four":
mailBoxTarget = '"[Gmail]/Important"'
SpeakText("Important Mails selected.")
elif cmb == "5" or cmb.lower() == "five":
mailBoxTarget = '"[Gmail]/Spam"'
SpeakText("Spam selected.")
elif cmb == "6" or cmb.lower() == "six":
mailBoxTarget = '"[Gmail]/Starred"'
SpeakText("Starred Mails selected.")
elif cmb == "7" or cmb.lower() == "seven":
mailBoxTarget = '"[Gmail]/Bin"'
SpeakText("Bin selected.")
else:
SpeakText("Wrong choice. Hence, default option Inbox wil be selected.")
M.select(mailBoxTarget)
SpeakText("Say 1 to search mails from a specific sender. Say 2 to search mail with respect to the subject of the mail.")
mailSearchChoice = speech_to_text()
if mailSearchChoice == "1" or mailSearchChoice.lower() == "one":
SpeakText("Please mention the sender email ID you want to search.")
searchSub = speech_to_text()
searchSub = searchSub.replace("at the rate", "@")
searchSub = searchSub.replace(" ", "")
status, messages = M.search(None, f'FROM "{searchSub}"')
elif mailSearchChoice == "2" or mailSearchChoice.lower() == "two" or mailSearchChoice.lower() == "tu":
SpeakText("Please mention the subject of the mail you want to search.")
searchSub = speech_to_text()
status, messages = M.search(None, f'SUBJECT "{searchSub}"')
else:
SpeakText("Wrong choice. Performing default operation. Please mention the subject of the mail you want to search.")
searchSub = speech_to_text()
status, messages = M.search(None, f'SUBJECT "{searchSub}"')
if str(messages[0]) == "b''":
SpeakText(f"Mail not found in {mailBoxTarget}.")
return None
msgCount = 1
for i in messages:
SpeakText(f"Message {msgCount}:")
res, msg = M.fetch(i, "(RFC822)") # fetch the email message by ID
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1]) # parse a bytes email into a message object
subject, encoding = decode_header(msg["Subject"])[0] # decode the email subject
if isinstance(subject, bytes):
subject = subject.decode(encoding) # if it's a bytes, decode to str
From, encoding = decode_header(msg.get("From"))[0] # decode email sender
if isinstance(From, bytes):
From = From.decode(encoding)
SpeakText("Subject: " + subject)
FromArr = From.split()
FromName = " ".join(namechar for namechar in FromArr[0:-1])
SpeakText("From: " + FromName)
SpeakText("Sender mail: " + FromArr[-1])
# MULTIPART
if msg.is_multipart():
for part in msg.walk(): # iterate over email parts
content_type = part.get_content_type() # extract content type of email
content_disposition = str(
part.get("Content-Disposition"))
try:
body = part.get_payload(decode=True).decode() # get the email body
except:
pass
# PLAIN TEXT MAIL
if content_type == "text/plain" and "attachment" not in content_disposition:
SpeakText("Do you want to listen to the text content of the mail ? Please say YES or NO.")
talkMSG1 = speech_to_text()
if "yes" in talkMSG1.lower():
SpeakText("The mail body contains the following:")
SpeakText(body)
else:
SpeakText("You chose NO")
# MAIL WITH ATTACHMENT
elif "attachment" in content_disposition:
SpeakText("The mail contains attachment, the contents of which will be saved in respective folders with it's name similar to that of subject of the mail")
filename = part.get_filename() # download attachment
if filename:
folder_name = clean(subject)
if not os.path.isdir(folder_name):
os.mkdir(folder_name) # make a folder for this email (named after the subject)
filepath = os.path.join(folder_name, filename)
open(filepath, "wb").write(part.get_payload(decode=True)) # download attachment and save it
# NOT MULTIPART
else:
content_type = msg.get_content_type() # extract content type of email
body = msg.get_payload(decode=True).decode() # get the email body
if content_type == "text/plain":
SpeakText("Do you want to listen to the text content of the mail ? Please say YES or NO.")
talkMSG2 = speech_to_text()
if "yes" in talkMSG2.lower():
SpeakText("The mail body contains the following:")
SpeakText(body)
else:
SpeakText("You chose NO")
# HTML CONTENTS
if content_type == "text/html":
SpeakText("The mail contains an HTML part, the contents of which will be saved in respective folders with it's name similar to that of subject of the mail. You can view the html files in any browser, simply by clicking on them.")
# if it's HTML, create a new HTML file
folder_name = clean(subject)
if not os.path.isdir(folder_name):
os.mkdir(folder_name) # make a folder for this email (named after the subject)
filename = "index.html"
filepath = os.path.join(folder_name, filename)
# write the file
open(filepath, "w").write(body)
# webbrowser.open(filepath) # open in the default browser
SpeakText(f"\nEnd of message {msgCount}:")
msgCount += 1
print("="*100)
M.close()
M.logout()
def main():
"""
Main function that handles primary choices
"""
if EMAIL_ID != "" and PASSWORD != "":
SpeakText("Choose and speak out the option number for the task you want to perform. Say 1 to send a mail. Say 2 to get your mailbox status. Say 3 to search a mail. Say 4 to get the last 3 mails.")
choice = speech_to_text()
if choice == '1' or choice.lower() == 'one':
composeMail()
elif choice == '2' or choice.lower() == 'too' or choice.lower() == 'two' or choice.lower() == 'to' or choice.lower() == 'tu':
getMailBoxStatus()
elif choice == '3' or choice.lower() == 'tree' or choice.lower() == 'three':
searchMail()
elif choice == '4' or choice.lower() == 'four' or choice.lower() == 'for':
getLatestMails()
else:
SpeakText("Wrong choice. Please say only the number")
else:
SpeakText("Both Email ID and Password should be present")
if __name__ == '__main__':
main()