Skip to content

Commit 9a4bf93

Browse files
Merge pull request #226 from AutomationSolutionz/second_random_email
Random email factory
2 parents 969e8d0 + c639774 commit 9a4bf93

File tree

3 files changed

+209
-104
lines changed

3 files changed

+209
-104
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# Version 16
55

66
### [Current changes]
7+
- **[Add]** Added secondary random mailbox
78
- **[Add]** Added Browser Performance metrics, Step metrics, Action metrics
89
- **[Add]** Import files in Execute Python Code action
910
- **[Add]** Added a reserved variable `zeuz_attachments_dir`

Framework/Built_In_Automation/Sequential_Actions/common_functions.py

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
import traceback
4141
import json
4242
from datetime import timedelta
43-
from .utility import send_email, check_latest_received_email, delete_mail, save_mail, RandomEmail1SecMail
43+
from .utility import send_email, check_latest_received_email, delete_mail, save_mail,random_mail_factory
4444
import re
4545

4646
months = [
@@ -4168,11 +4168,17 @@ def random_email_generator(data_set):
41684168
if var_variable is None:
41694169
CommonUtil.ExecLog(sModuleInfo, "Please provide variable name to store results", 3)
41704170
return "zeuz_failed"
4171+
mail_fac = random_mail_factory()
4172+
var_email_creds = mail_fac.connection_creds #return random email address
41714173

4172-
var_email = RandomEmail1SecMail.create_random_email_address() #return random email address
4173-
4174-
CommonUtil.ExecLog(sModuleInfo, "Created random email address '%s' " % (var_email), 1)
4175-
return sr.Set_Shared_Variables(var_variable, var_email) #saved in shared variable inside variable key
4174+
if var_email_creds == {}:
4175+
CommonUtil.ExecLog(sModuleInfo, "Unable to create random mailbox", 3)
4176+
return "zeuz_failed"
4177+
4178+
CommonUtil.ExecLog(sModuleInfo, "Created random email address '%s' " % (var_email_creds), 1)
4179+
sr.Set_Shared_Variables("random_email_factory", mail_fac)
4180+
return sr.Set_Shared_Variables(var_variable, var_email_creds) #saved in shared variable inside variable key
4181+
41764182

41774183
except:
41784184
return CommonUtil.Exception_Handler(sys.exc_info())
@@ -4219,8 +4225,11 @@ def random_email_read(data_set):
42194225
CommonUtil.ExecLog(sModuleInfo, "Waiting for %s seconds to receive the mail" % (wait), 1)
42204226
start = time.time()
42214227
while True:
4222-
res = RandomEmail1SecMail.checkMails(var_email)
4223-
if len(res[var_email]) > 0:
4228+
mail_fac = sr.Get_Shared_Variables("random_email_factory")
4229+
if isinstance(var_email,str):
4230+
var_email = eval(var_email)
4231+
res = mail_fac.checkMails(var_email)
4232+
if len(res[var_email['email']]) > 0:
42244233
break
42254234
if start + wait < time.time():
42264235
CommonUtil.ExecLog(sModuleInfo, "No email found for '%s' after waiting %s seconds. You may need to increase wait time" % (var_email, wait), 1)
@@ -4256,8 +4265,10 @@ def random_email_delete(data_set):
42564265
if var_email is None:
42574266
CommonUtil.ExecLog(sModuleInfo, "Please provide email address", 3)
42584267
return "zeuz_failed"
4259-
4260-
res = RandomEmail1SecMail.deleteMail(var_email)
4268+
mail_fac = sr.Get_Shared_Variables("random_email_factory")
4269+
if isinstance(var_email,str):
4270+
var_email = eval(var_email)
4271+
res = mail_fac.deleteMailBox(var_email)
42614272

42624273
if res:
42634274
CommonUtil.ExecLog(sModuleInfo, "'%s' is deleted" % (var_email), 1)

Framework/Built_In_Automation/Sequential_Actions/utility.py

Lines changed: 188 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from Framework.Utilities import CommonUtil
2222
import inspect
2323
from Framework.Built_In_Automation.Shared_Resources import BuiltInFunctionSharedResources as sr
24-
24+
from bs4 import BeautifulSoup
2525

2626
# using IMAP protocol
2727
from Framework.Utilities.CommonUtil import MODULE_NAME
@@ -185,100 +185,6 @@ def send_email(
185185
server.sendmail(sender_email, receiver_email, text)
186186
print("email sent successfully")
187187

188-
189-
class RandomEmail1SecMail:
190-
191-
"""
192-
usage: This class is used for randomly creating email,read inbox emails from that email and delete that email
193-
sources: 1secmail api services
194-
"""
195-
196-
197-
@staticmethod
198-
def generateRandomUserName(): #this function used for generating random username
199-
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
200-
name = string.ascii_lowercase + string.digits #name with letters and digits
201-
username = ''.join(random.choice(name) for i in range(10)) #randomly generating username
202-
return username
203-
204-
@staticmethod
205-
def extract(newMail): #this function is used for getting username and domain part from modified api
206-
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
207-
getUserName = re.search(r'login=(.*)&',newMail).group(1) #parseUsername part
208-
getDomain = re.search(r'domain=(.*)', newMail).group(1) #parseDomainname part
209-
return [getUserName, getDomain]
210-
211-
@staticmethod
212-
def create_random_email_address(): #this function is used for creating random email address
213-
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
214-
API = 'https://www.1secmail.com/api/v1/' #1secmail api for creating random email
215-
domainList = ['1secmail.com', '1secmail.net', '1secmail.org'] # 1secmail domain list
216-
domain = random.choice(domainList) #randomly selecting a domain
217-
newMail = f"{API}?login={RandomEmail1SecMail.generateRandomUserName()}&domain={domain}" #generateRandomUserName() return random username and call api to create
218-
reqMail = requests.get(newMail)
219-
mail = f"{RandomEmail1SecMail.extract(newMail)[0]}@{RandomEmail1SecMail.extract(newMail)[1]}" #extract(newMail) return list[username,domain_name]
220-
return mail
221-
222-
@staticmethod
223-
def checkMails(newMail): #this function is used for getting all the inbox mails for that random email
224-
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
225-
API = 'https://www.1secmail.com/api/v1/' #1secmail api
226-
var_mails=[]
227-
reqLink = f'{API}?action=getMessages&login={newMail.split("@")[0]}&domain={newMail.split("@")[1]}' #Api for getting mail list
228-
req = requests.get(reqLink).json()
229-
length = len(req)
230-
if length == 0:
231-
return {newMail:[]}
232-
else:
233-
idList = []
234-
for i in req:
235-
for k,v in i.items():
236-
if k == 'id':
237-
mailId = v
238-
idList.append(mailId) #collecting all mailid which is in Inbox
239-
240-
for i in idList:
241-
var_mail_info = {}
242-
msgRead = f'{API}?action=readMessage&login={newMail.split("@")[0]}&domain={newMail.split("@")[1]}&id={i}' #api for collect msgbody using mailid
243-
req = requests.get(msgRead).json()
244-
var_mail_info['id']=i
245-
for k,v in req.items(): #sepating elements from mail
246-
if k == 'from':
247-
sender = v
248-
var_mail_info['sender']=sender
249-
elif k == 'subject':
250-
subject = v
251-
var_mail_info['subject']=subject
252-
elif k == 'date':
253-
date = v
254-
var_mail_info['date']=date
255-
elif k == 'textBody':
256-
content = v
257-
var_mail_info['content']=content
258-
elif k == 'body':
259-
body = v
260-
var_mail_info['body']=body
261-
elif k == 'htmlBody':
262-
htmlBody = v
263-
var_mail_info['content']=htmlBody
264-
var_mails.append(var_mail_info)
265-
266-
return {newMail:var_mails}
267-
268-
@staticmethod
269-
def deleteMail(newMail): #this function is used for delete that random email
270-
url = 'https://www.1secmail.com/mailbox'
271-
data = {
272-
'action': 'deleteMailbox',
273-
'login': f'{newMail.split("@")[0]}',
274-
'domain': f'{newMail.split("@")[1]}'
275-
}
276-
req = requests.post(url, data=data)
277-
if req.status_code==200:
278-
return True
279-
return False
280-
281-
282188
def delete_mail(
283189
imap_host,
284190
imap_user,
@@ -437,3 +343,190 @@ def gt(dt):
437343
f.write(att.payload)
438344

439345
return value
346+
347+
import string,re,random,requests,json
348+
from abc import ABC, abstractmethod
349+
350+
class RandomMailBoxExporter(ABC):
351+
352+
connection_creds = None
353+
354+
@abstractmethod
355+
def get_random_mailbox(self):
356+
"""Create MailBox on the service. Returns credentials in form of dict"""
357+
358+
@abstractmethod
359+
def checkMails(self):
360+
"""Returns a list of messages from the mailbox"""
361+
362+
@abstractmethod
363+
def deleteMailBox(self):
364+
"""Delete mailbox. Returns True or False"""
365+
366+
class RandomEmail1SecMail(RandomMailBoxExporter):
367+
368+
@staticmethod
369+
def generateRandomUserName(): #this function used for generating random username
370+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
371+
name = string.ascii_lowercase + string.digits #name with letters and digits
372+
username = ''.join(random.choice(name) for i in range(10)) #randomly generating username
373+
return username
374+
375+
@staticmethod
376+
def extract(newMail): #this function is used for getting username and domain part from modified api
377+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
378+
getUserName = re.search(r'login=(.*)&',newMail).group(1) #parseUsername part
379+
getDomain = re.search(r'domain=(.*)', newMail).group(1) #parseDomainname part
380+
return [getUserName, getDomain]
381+
382+
@staticmethod
383+
def get_random_mailbox(): #this function is used for creating random email address
384+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
385+
API = 'https://www.1secmail.com/api/v1/' #1secmail api for creating random email
386+
domainList = ['1secmail.com', '1secmail.net', '1secmail.org'] # 1secmail domain list
387+
domain = random.choice(domainList) #randomly selecting a domain
388+
newMail = f"{API}?login={RandomEmail1SecMail.generateRandomUserName()}&domain={domain}" #generateRandomUserName() return random username and call api to create
389+
reqMail = requests.get(newMail)
390+
mail = f"{RandomEmail1SecMail.extract(newMail)[0]}@{RandomEmail1SecMail.extract(newMail)[1]}" #extract(newMail) return list[username,domain_name]
391+
return {'email':mail,'api_key':''}
392+
393+
@staticmethod
394+
def checkMails(newMailCreds): #this function is used for getting all the inbox mails for that random email
395+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
396+
newMail = newMailCreds['email']
397+
API = 'https://www.1secmail.com/api/v1/' #1secmail api
398+
var_mails=[]
399+
reqLink = f'{API}?action=getMessages&login={newMail.split("@")[0]}&domain={newMail.split("@")[1]}' #Api for getting mail list
400+
req = requests.get(reqLink).json()
401+
length = len(req)
402+
if length == 0:
403+
return {newMail:[]}
404+
else:
405+
idList = []
406+
for i in req:
407+
for k,v in i.items():
408+
if k == 'id':
409+
mailId = v
410+
idList.append(mailId) #collecting all mailid which is in Inbox
411+
412+
for i in idList:
413+
var_mail_info = {}
414+
msgRead = f'{API}?action=readMessage&login={newMail.split("@")[0]}&domain={newMail.split("@")[1]}&id={i}' #api for collect msgbody using mailid
415+
req = requests.get(msgRead).json()
416+
var_mail_info['id']=i
417+
for k,v in req.items(): #sepating elements from mail
418+
if k == 'from':
419+
sender = v
420+
var_mail_info['sender']=sender
421+
elif k == 'subject':
422+
subject = v
423+
var_mail_info['subject']=subject
424+
elif k == 'date':
425+
date = v
426+
var_mail_info['date']=date
427+
elif k == 'textBody':
428+
content = v
429+
var_mail_info['content']=content
430+
elif k == 'body':
431+
body = v
432+
var_mail_info['body']=body
433+
elif k == 'htmlBody':
434+
htmlBody = v
435+
var_mail_info['content']=htmlBody
436+
var_mails.append(var_mail_info)
437+
438+
return {newMail:var_mails}
439+
440+
@staticmethod
441+
def deleteMailBox(newMailCreds): #this function is used for delete that random email
442+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
443+
newMail = newMailCreds['email']
444+
url = 'https://www.1secmail.com/mailbox'
445+
data = {
446+
'action': 'deleteMailbox',
447+
'login': f'{newMail.split("@")[0]}',
448+
'domain': f'{newMail.split("@")[1]}'
449+
}
450+
req = requests.post(url, data=data)
451+
if req.status_code==200:
452+
return True
453+
return False
454+
455+
class TempEmailDevelopermail(RandomMailBoxExporter):
456+
name = None
457+
headers = {
458+
'accept': 'application/json'
459+
}
460+
all_mail_ids = []
461+
462+
463+
def get_random_mailbox(self):
464+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
465+
url = "https://www.developermail.com/api/v1/mailbox"
466+
response = requests.request("PUT", url, headers=self.headers)
467+
response_body = json.loads(response.text)
468+
self.name = response_body["result"]["name"]
469+
token = response_body["result"]["token"]
470+
random_email_creds = {"email":self.name + "@developermail.com","api_key":token}
471+
return random_email_creds
472+
473+
474+
def check_mailbox(self,creds):
475+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
476+
self.name = creds['email'].split('@')[0].strip()
477+
self.headers['X-MailboxToken'] = creds['api_key']
478+
url = f"https://www.developermail.com/api/v1/mailbox/{self.name}"
479+
response = requests.request("GET", url, headers=self.headers)
480+
response_body = json.loads(response.text)
481+
self.all_mail_ids = response_body['result']
482+
483+
def checkMails(self,creds):
484+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
485+
self.check_mailbox(creds)
486+
url = f"https://www.developermail.com/api/v1/mailbox/{self.name}/messages"
487+
payload = json.dumps(self.all_mail_ids)
488+
self.headers["Content-Type"] = "application/json"
489+
response = requests.request("POST", url, headers=self.headers, data=payload)
490+
response_body = json.loads(response.text)
491+
var_mails = []
492+
results = response_body['result']
493+
if results:
494+
for result in results:
495+
var_mail_info = dict()
496+
value = result["value"]
497+
var_mail_info['id'] = result["key"]
498+
var_mail_info['sender'] = value.split("\r\nFrom:")[-1].split("\r\nDate:")[0].split("<")[-1].split('>')[0].strip()
499+
var_mail_info['subject'] = value.split("\r\nSubject:")[-1].split("\r\nTo:")[0].strip()
500+
var_mail_info['date'] = value.split("\r\nDate:")[-1].split("\r\n")[0].strip()
501+
var_mail_info['body'] = value.split("Content-Type: text/html;")[-1].split('--')[0].strip().split('\r\n\r\n')[-1].strip()
502+
var_mail_info['content'] = BeautifulSoup(var_mail_info["body"],'html.parser').get_text(separator="\n")
503+
504+
var_mails.append(var_mail_info)
505+
return {creds['email']: var_mails}
506+
507+
def deleteMailBox(self,creds):
508+
sModuleInfo = inspect.currentframe().f_code.co_name + " : " + MODULE_NAME
509+
self.name = creds['email'].split('@')[0].strip()
510+
url = f"https://www.developermail.com/api/v1/mailbox/{self.name}"
511+
self.headers['X-MailboxToken'] = creds['api_key']
512+
response = requests.request("DELETE", url, headers=self.headers)
513+
response_body = json.loads(response.text)
514+
return response_body.get('success')
515+
516+
517+
def random_mail_factory() -> RandomMailBoxExporter:
518+
"""Constructs an exporter factory based on service availability"""
519+
520+
factories = [RandomEmail1SecMail(),TempEmailDevelopermail()]
521+
522+
for factory in factories:
523+
if factory.connection_creds == None:
524+
try:
525+
mail_creds = factory.get_random_mailbox()
526+
except:
527+
mail_creds = {}
528+
factory.connection_creds = mail_creds
529+
if mail_creds.get('email'):
530+
return factory
531+
else:
532+
return factory

0 commit comments

Comments
 (0)