def __init__(self, filter_processor, definition): self.definition = definition self.filter_processor = filter_processor self.logger = filter_processor.logger self.server = definition["server"] self.user = definition["user"] self.password = definition["password"] self.to_expunge = False self.select_result = None self.folders = None self.search_all_result_set = None self.folder_cache = {} try: self.M = imapclient.IMAPClient(self.server, ssl=True) except IMAP4.error: ssl_context = ssl.create_default_context() self.M = imapclient.IMAPClient(self.server, ssl_context=ssl_context, ssl=True) for token in set(self.definition.keys()) - set( BaseFilterProcessorElement.tokens): if token not in self.tokens: raise Exception( 'Playbook : "%s" Imap_client : "%s" unknown token : "%s"\nAvailable tokens : ' % (self.filter_processor.current_playbook, self.definition["name"], token))
def notify(): global notiy_alert, server alls = server.search(["ALL"]) first = True last = len(alls) while notify_alert: try: ser = imapclient.IMAPClient(imap, ssl=True) ser.login(email, base64.decodestring(password)) dir = ser.select_folder("INBOX") alls = ser.search(["ALL"]) if len(alls) > last: if first: last = len(alls) else: wave_sound.play() last = len(alls) server = imapclient.IMAPClient(imap, ssl=True) server.login(email, base64.decodestring(password)) dir = server.select_folder("INBOX") last_item = int(alls[int(len(alls) - 1)]) getinfo = get_info(last_item) from_n = getinfo[1] from_e = getinfo[0] print "\n\x1b[33m[*]New Email from {0} / {1}\x1b[39m".format( from_e, from_n) first = False ser.logout() except: refresh() noitfy_alert = False
def getInstructionEmails(): # imapClientでログイン logging.debug('Connecting to IMAP server at %s...' % (IMAP_SERVER)) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) imapCli = imapclient.IMAPClient(IMAP_SERVER, ssl=True, ssl_context=context) imapCli.login(BOT_EMAIL, BOT_EMAIL_PASSWORD) imapCli.select_folder('INBOX') logging.debug('Connected.') # メールから命令を取得 instructions = [] UIDs = imapCli.search(['FROM', MY_EMAIL]) rawMessages = imapCli.fetch(UIDs, ['BODY[]']) for UID in rawMessages.keys(): # 生のメッセージを解析 message = pyzmail.PyzMessage.factory(rawMessages[UID][b'BODY[]']) if message.html_part != None: body = message.html_part.get_payload().decode( message.html_part.charset) if message.text_part != None: # HTMLとテキストの両方があればテキストの方を用います body = message.text_part.get_payload().decode( message.text_part.charset) # メール本文から命令を抽出 instructions.append(body) # 受信したメールを削除する。 if len(UIDs) > 0: imapCli.delete_messages(UIDs) imapCli.expunge() imapCli.logout() return instructions
def connect(self): self.server = imapclient.IMAPClient(self.server_address, ssl_context=self.ssl_context, use_uid=False) self.server.login(self.username, self.password) self.server.select_folder(self.mailbox) self.logger.info(f"Connected to mailbox {self.mailbox}")
def unsub(user_name, user_pass): #empty unsub list unsub_list = [] #maximline with imaplib imaplib._MAXLINE(10000) #place email whitch to use and log in ima_login = imapclient.IMAPClient('imap.gmail.com', ssl=True) ima_login.login(user_name,user_pass) imap_obj = ima_login.select_folder('INBOX', readonly=True) #select folder and search ALL unique_ids = imap_obj.search('ALL') for identifier in unique_ids: #fetch from identifier body and flags raw_message = imap_obj.fetch([identifier], ['BODY[]'], 'FLAGS']) #message use pyzail mpymessage factory raw message identifier b body message = pyzmail.PyzMessage.factory(raw_message[identifier][b'BODY[]']) #html message pget html part get payload and decode message hmtl part charset html = message.html_part.get_payload().decode(message.html_part.charset) soup = bs4.BeautifulSoup(html, 'lxml') link_elem = soup.select('a') for selected in link_elem: if 'unsubscribe' in selected: unsub_list.append(selected.get('href')) imap_obj.logout() return unsub_list
def get_email(): # Connect to server server = imapclient.IMAPClient(imap_host, ssl=True) server.login(imap_user, imap_pass) server.select_folder('Inbox', readonly=False) ## Identifying new delivery notes correct_to = server.search(['TO', '*****@*****.**']) # only emails to deliveries correct_from = server.search(['FROM', '*****@*****.**']) # only emails from holger.ritter # print(set.intersection(set(correct_to), set(correct_from))) # visaul validation of emails with two criteria correct_to_from = set.intersection(set(correct_to), set(correct_from)) # intersection of from and to addresses # create functions here (fetching, reading, finding attachments, writing pdfs) for uid, msg_data in server.fetch(correct_to_from, 'RFC822').items(): email_message = email.message_from_bytes(msg_data[b'RFC822']) if email_message.get_content_maintype() == 'multipart': for part in email_message.walk(): attachment_filename = part.get_filename() if attachment_filename is not None: print("File name: ", part.get_filename()) # visual confirmation attachment_path = f'{attachments_folder}/{attachment_filename}' with open(attachment_path, 'wb') as fp: fp.write(part.get_payload(decode=True)) fp.close() pdf_extract() server.move(uid, 'Delivery_Archive')
def __loginIMAP(self): try: self.imapObj = imapclient.IMAPClient("imap.gmail.com", ssl=True) self.imapObj.login(self.userName, self.pswd) print("IMAP login successful..") except: print("There was an error connecting to IMAP..")
def downloadMovie(): while True: print('Logging into account...') imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True) imapObj.login(username, password) print('Reading mail...') imapObj.select_folder('INBOX', readonly=False) UIDs = imapObj.search(['ALL']) if len(UIDs) > 0: rawMessages = imapObj.fetch(UIDs, ['BODY[]']) #pprint.pprint(rawMessages) for v in rawMessages.values(): message = pyzmail.PyzMessage.factory(v[b'BODY[]']) subject = message.get_subject() fromAddr = message.get_addresses('from') bitTorrentLink = message.text_part.get_payload().decode( message.text_part.charset) # Creating smtp connection smtpObj = smtplib.SMTP('smtp.gmail.com', 587) smtpObj.ehlo() smtpObj.starttls() if downloadPassword == subject: print('Starting movie downloading...') torrentProcess = subprocess.Popen( ['/usr/bin/qbittorrent', bitTorrentLink]) imapObj.delete_messages(UIDs) torrentProcess.wait() # Sending a success mail print("Movie downloaded successfully.") smtpObj.login(username, password) mailText = 'Subject: Movie downloaded successfully.\nYour movie has been successfully downloaded.' smtpObj.sendmail(username, fromAddr[0][1], mailText) smtpObj.quit() else: print( "Password didn't match.\nSending mail back to sender for incorrect password." ) smtpObj.login(username, password) mailText = 'Subject: Incorrect password.\nPlease send correct password in subject' smtpObj.sendmail(username, fromAddr[0][1], mailText) imapObj.delete_messages(UIDs) smtpObj.quit() else: print('No email found.') imapObj.logout() # sleep for 10 minutes for i in range(10): time.sleep(60)
def imap_login(self): m = imapclient.IMAPClient(self.imap_server.host, use_uid=False, ssl=self.imap_server.use_ssl) m.login(self.username, self.password) return m
def post(self, request): client = imapclient.IMAPClient('imap.yandex.ru') try: client.oauth2_login('*****@*****.**', 'AgAAAAA9U6WoAAZmeTTDasOXdE9usp_-zAmOL_E') except: raise ValidationError('an error occured in yandex mail server') serializer = EmailFolderMoveSerializer(data=request.data) serializer.is_valid() mail_uids = serializer.validated_data['uids'] from_folder = serializer.validated_data['from_folder'] to_folder = serializer.validated_data['to_folder'] emails = Email.objects.filter( num__in=mail_uids, ).filter(folder=from_folder).order_by('-num') print(mail_uids) print(emails) client.select_folder(from_folder) client.move(mail_uids, to_folder) client.select_folder(to_folder) new_uids = client.search(['RECENT', 'NOT', 'UNSEEN'])[::-1] print(new_uids) print(emails) for index, email in enumerate(emails): email.folder = to_folder email.flag = 'Seen' email.num = new_uids[index] email.save() return Response({'mails': 'moved succesfully'})
def magnet_check(): # Checks Gmail for Magnet links from verified address and returns them imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True) imapObj.login(BOT_EMAIL, BOT_PASS) imapObj.select_folder('INBOX', readonly=True) UIDs = imapObj.search(['FROM', VERIFIED_EMAIL]) magnets = [] if UIDs: for identifier in UIDs: rawMessage = imapObj.fetch([identifier], ['BODY[]', 'FLAGS']) message = pyzmail.PyzMessage.factory( rawMessage[identifier][b'BODY[]']) subject = message.get_subject() #message.text_part.get_payload().decode(message.text_part.charset) if VERIFICATION_PASS in subject: text = message.text_part.get_payload().decode( message.text_part.charset) magnets.append(text) #imapObj.delete_messages(UIDs) #imapObj.expunge() imapObj.logout() return magnets
def connect_email_info(): """ Get Exchange account connection with server """ imapObj = imapclient.IMAPClient('imap-mail.outlook.com', ssl=True) imapObj.login(' [email protected] ', ' Password ') imapObj.select_folder('INBOX', readonly=True) unique_ids = [] UIDs = imapObj.search(['ALL']) for IDs in UIDs: unique_ids.append(IDs) # print(unique_ids) message_id = unique_ids # print(message_id) rawMessages = imapObj.fetch(message_id, ['BODY[]', 'FLAGS']) email_ids = 0 for email_ids in rawMessages: message = pyzmail.PyzMessage.factory(rawMessages[email_ids][b'BODY[]']) print( "\n===============================================================" ) print( "******Messages from INBOX folder separated with this lines*****") print( "===============================================================\n" ) print(f"\nFrom: {message.get_addresses('from')}\n") print(f"To: {message.get_addresses('to')}\n") print(f"Subject: {message.get_subject()}\n") print(message)
def example_ip_clean(): host = 'imap.gmail.com' server = imapclient.IMAPClient(host, use_uid=True, ssl=True) server.login('*****@*****.**', 'Mu7t1p1aF1at') server.select_folder('INBOX') for crit in 'FROM "*****@*****.**"', : message_ids = server.search([crit]) message_ids = [ msg_id for msg_id in message_ids if not exists(join(root_mail, str(msg_id))) ] #msgs = server.fetch(message_ids, ['INTERNALDATE']) msgs = server.fetch(message_ids, ['INTERNALDATE', 'RFC822']) for k, v in msgs.items(): e = email.message_from_string(v['RFC822']) print e.get('Received') for part in e.walk(): # Save the contents: path = join(root_mail, str(k)) if not exists(path): os.makedirs(path) if part.get_filename(): filename = part.get_filename() open(join(path, filename), 'wb').write(part.get_payload(decode=1)) for dirpath, dirnames, filenames in os.walk(root_mail): path_dest = r"P:\data\source\kpn\ip_cleaner\reports" for filename in filenames: if re.match('ip_cleaner_.*_\d+\-\d+\-\d+\.csv', filename): if not os.path.exists(join(path_dest, filename)): shutil.copy2(join(dirpath, filename), path_dest)
def recv_imap(): imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True) print('User Email:') usr_id = input() print('Password:'******'Access which folder:') fol = input() s = imapObj.select_folder(fol, readonly=True) print(s) print('Wanna search anything?') s = input() s = imapObj.search(['ALL']) print(s) print('which mail?') UID = input() print(UID) raw_mess = imapObj.fetch([UID], ['BODY[]', 'FLAGS']) print(raw_mess) # mess = pyzmail.PyzMessage.factory(raw_mess[UID]['BODY[]']) # print(mess + ' ' + mess.get_subject() + ' ' + mess.get_addresses('from') + ' ' + mess.get_addresses('to')) s = imapObj.logout() print(s)
def take_action(self, args): self.args = args try: account = self.app.config['accounts'][args.account] except (TypeError, KeyError): raise exceptions.NoSuchAccount( 'Unable to find account named "%s"' % args.account) self.server = imapclient.IMAPClient(account['host'], use_uid=True, ssl=account.get('ssl', True)) self.server.debug = args.debug_imap self.server.login(account['username'], account['password']) selected_folders = self.select_folders(args.folders) if not selected_folders: raise exceptions.NoMatchingFolders('No folders to process') if args.fail_if_empty and len(selected_folders) > 1: raise exceptions.InvalidOptions( '--fail-if-empty can only be used when processing ' 'a single folder') self.process_folders(selected_folders)
def check_torrents(email, password): imaplib._MAXLINE = 10000000 imap_obj = imapclient.IMAPClient('imap.gmail.com', ssl=True) imap_obj.login(email, password) imap_obj.select_folder('INBOX', readonly=True) uids = imap_obj.search(['FROM ' + VERIFIED_EMAIL]) links = [] if uids: for idenitifier in uids: raw_messages = imap_obj.fetch([idenitifier], ['BODY[]', 'FLAGS']) message = pyzmail.PyzMessage.factory( raw_messages[idenitifier][b'BODY[]']) text = message.text_part.get_payload().decode( message.text_part.charset) if VERIFIED_PASS in text: html = message.html_part.get_payload().decode( message.html_part.charset) links.append(html) imap_obj.delete_messages(uids) imap_obj.expunge() imap_obj.logout() return links
def takemail(): connect = imapclient.IMAPClient(mailaddr) try: connect.login(usr, passwd) except Exception as err: print('登陆失败:', err) bodys = [] deletemail = [] connect.select_folder('INBOX') msno = connect.search('FROM' + sender) maildict = connect.fetch(msno, ['BODY[]']) for uid in maildict.keys(): message = pyzmail.PyzMessage.factory(maildict[uid][b'BODY[]']) if message.text_part != None: body = message.text_part.get_payload().decode( message.text_part.charset) deletemail.append(uid) elif message.html_part != None: body = message.html_part.get_payload().decode( message.html_part.charset) deletemail.append(uid) bodys.append(body) # 找到相应的正文后删除邮件 if len(deletemail) > 0: connect.delete_messages(deletemail) connect.expunge() connect.logout() #将正文的内容返回 return bodys
def readEmail(self): ''' Brings in unread emails and parses out the body of the email if the email is from self.RECEIVER ''' imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True) imapObj.login(self.SENDER, self.PASSWORD) imapObj.select_folder('INBOX', readonly=True) now = datetime.datetime.now() yesterday = (now + datetime.timedelta(days=-1)).strftime('%d-%b-%Y') UIDs = imapObj.search([u'SINCE', yesterday, u'UNSEEN']) messages = [] for i in UIDs: if i not in self.seenIDs: rawMessage = imapObj.fetch(i, 'BODY[]') msg = email.message_from_bytes(rawMessage[i][b'BODY[]']) if msg['from'].split()[-1] == '<{}>'.format(self.RECEIVER): if msg.is_multipart: multi = msg.get_payload() for j in multi: temp = j.get_payload() if temp[0] != '<': messages.append(j.get_payload()[:-2]) else: messages.append(msg.get_payload()[:-2]) self.seenIDs.append(i) return messages
def unsubscribe(imap_address, email_address, password): """Checks unsubscribe links within emails and opens link Args: imap_address (str): email providers imap address email_address (str): email address password (str): password for email Returns: None """ imaplib._MAXLINE = 10000000 imapObj = imapclient.IMAPClient(imap_address, ssl=True) # See https://support.google.com/accounts/answer/6010255 if (Login Error) imapObj.login(email_address, password) imapObj.select_folder('INBOX', readonly=True) UIDs = imapObj.search(['ALL']) for u in UIDs: rawMessages = imapObj.fetch([u], ['BODY[]', 'FLAGS']) message = pyzmail.PyzMessage.factory(rawMessages[u][b'BODY[]']) if message.html_part: html = message.html_part.get_payload().decode( message.html_part.charset) soup = bs4.BeautifulSoup(html, 'html.parser') linkElems = soup.select('a') for link in linkElems: if 'unsubscribe' in link.text.lower(): url = link.get('href') print('opening {}: '.format(url)) webbrowser.open(url) imapObj.logout()
def getInstructionEmails(): # Log in to the email imapCli. logging.debug('Connecting to IMAP server at %s...' % (IMAP_SERVER)) imapCli = imapclient.IMAPClient(IMAP_SERVER, ssl=True) imapCli.login(BOT_EMAIL, BOT_EMAIL_PASSWORD) imapCli.select_folder('INBOX') logging.debug('Connected.') # Fetch all instruction emails. instructions = [] UIDs = imapCli.search(['FROM ' + MY_EMAIL]) rawMessages = imapCli.fetch(UIDs, ['BODY[]']) for UID in rawMessages.keys(): # Parse the raw email message. message = pyzmail.PyzMessage.factory(rawMessages[UID]['BODY[]']) if message.html_part != None: body = message.html_part.get_payload().decode( message.html_part.charset) if message.text_part != None: # (if there's both an html and text part, use the text part) body = message.text_part.get_payload().decode( message.text_part.charset) # Extract instruction from email body. instructions.append(body) # Delete the instruction emails, if there are any. if len(UIDs) > 0: imapCli.delete_messages(UIDs) imapCli.expunge() imapCli.logout() return instructions
def receive_messages(self): self.askForConfig() connection = imapclient.IMAPClient(self.server, ssl=True, port=self.port) connection.login(self.login, self.password) connection.select_folder('INBOX', readonly=True) uids = connection.search("ALL") for uid in uids: htmlPart = "" textPart = "" rawMessage = connection.fetch(uid, 'BODY[]') formattedMessage = pyzmail.PyzMessage.factory( rawMessage[uid][b"BODY[]"]) sender = formattedMessage.get_decoded_header("From") subject = formattedMessage.get_decoded_header("Subject") date = formattedMessage.get_decoded_header("Date").split(",")[-1] date = date.lstrip() try: if formattedMessage.text_part: textPart = formattedMessage.text_part.get_payload().decode( formattedMessage.text_part.charset) if formattedMessage.html_part: htmlPart = formattedMessage.html_part.get_payload().decode( formattedMessage.html_part.charset) content = textPart + htmlPart except Exception: content = "Unable to load charset" self.messages.insert(0, Message(sender, subject, date, content, uid)) if len(self.messages) >= 20: break connection.logout()
def __init__(self, cfg): super().__init__(cfg) # Use default client behavior if ca_file not provided. context = imapclient.create_default_context() if 'ca_file' in cfg['server']: context.cafile = cfg['server']['ca_file'] if 'check_hostname' in cfg['server']: context.check_hostname = tobool(cfg['server']['check_hostname']) ssl = True if 'ssl' in cfg['server']: ssl = tobool(cfg['server']['ssl']) self._conn = imapclient.IMAPClient( cfg['server']['hostname'], use_uid=True, ssl=ssl, port=cfg['server'].get('port'), ssl_context=context, ) username = cfg['server']['username'] password = secrets.get_password(cfg) self._conn.login(username, password) self._mbox_names = None
def copy_to_sent_and_mark_deleted(mails, cfg): """ 1. Log in to the email server. 2. APPEND sent message to Sent folder 3. If successful, *flag* original message as \\Deleted 4. Expunge (have server actually delete them). """ with imapclient.IMAPClient(cfg.IMAP_SERVER, ssl=True) as server: server.login(cfg.MAILDOG_EMAIL, cfg.MAILDOG_EMAIL_PASSWORD) server.select_folder('INBOX') # UIDs = server.search("ANSWERED") logging.debug('Connected. %s' % server.welcome) results = {} for msg in mails: res_append = server.append('Sent', msg.reply_message.as_string(), [r'\Seen']) if b'APPEND completed' in res_append and msg.reply: res_mark = server.add_flags(msg.uid, [r'\Seen', r'\Deleted']) # server.move(UIDs, imapclient.imapclient.SENT) # server.move(UIDs, # server.find_special_folder(imapclient.imapclient.SENT)) results[msg.uid] = res_append # Delete the emails, if there are any. # server.expunge() return results
def listFoldersImap(email, password, imapPort): imapObj = imapclient.IMAPClient(imapPort, ssl=True) imapObj.login(email, password) print('listing folder inbox') pprint.pprint(imapObj.list_folders()) imapObj.logout() print('Logging out')
def imap_login(config): log = logging.getLogger() # Connect to IMAP try: imap = imapclient.IMAPClient(host=config.get('imap', 'host'), use_uid=True, ssl=True) log.debug('Connected to IMAP host %s', config.get('imap', 'host')) except BaseException as e: log.critical('Could not connect to IMAP host %s', config.get('imap', 'host')) log.critical('%s', e) import traceback traceback.print_exception(e.__class__, e, e.__traceback__) sys.exit(1) try: imap.login(config.get('imap', 'user'), config.get('imap', 'password')) log.debug('Logged in on IMAP host as %s', config.get('imap', 'user')) except BaseException: log.critical('Could not login on IMAP host as %s', config.get('imap', 'user')) sys.exit(1) try: folder = config.get('general', 'folder') imap.select_folder(folder) except BaseException: log.critical('Cannot select mailbox %s', folder) sys.exit(1) return imap
def magnet_check(): """Checks Gmail for Magnet links from verified address and returns them.""" imap_obj = imapclient.IMAPClient('imap.gmail.com', ssl=True) imap_obj.login(BOT_EMAIL, BOT_PASS) imap_obj.select_folder('INBOX') unique_ids = imap_obj.search(['FROM ' + VERIFIED_EMAIL]) magnets = [] if unique_ids: for identifier in unique_ids: raw_message = imap_obj.fetch([identifier], ['BODY[]', 'FLAGS']) message = pyzmail.PyzMessage.factory( raw_message[identifier][b'BODY[]']) text = message.text_part.get_payload().decode( message.text_part.charset) if VERIFICATION_PASS in text: html = message.html_part.get_payload().decode( message.html_part.charset) magnets.append(html) imap_obj.delete_messages(unique_ids) imap_obj.expunge() imap_obj.logout() return magnets
def take_action(self, args): self.args = args try: account = self.app.config['accounts'][args.account] except (TypeError, KeyError): raise exceptions.NoSuchAccount( 'Unable to find account named "%s"' % args.account) with open(args.filters) as fd: filters = yaml.load(fd) self.filters = self.build_filters(filters) self.server = imapclient.IMAPClient(account['host'], use_uid=True, ssl=account.get('ssl', True)) self.server.debug = args.debug_imap self.server.login(account['username'], account['password']) selected_folders = self.select_folders(args.folders) if not selected_folders: raise exceptions.NoMatchingFolders('No folders to process') self.process_folders(selected_folders)
def read_mail(): try: print('###########') print('Reading mails from a gmail account') print('###########') mail = imapclient.IMAPClient('imap.gmail.com', ssl=True) email = raw_input("Enter email account [[email protected]]: ") password = raw_input("Enter password account [default]: ") if email == "" and password == "": email = '*****@*****.**' password = '******' mail.login(email, password) else: mail.login(email, password) mail.select_folder('INBOX', readonly=True) UIDs = mail.search("ALL") for line in UIDs: rawMessages = mail.fetch([line], ['BODY[]', 'FLAGS']) message = pyzmail.PyzMessage.factory(rawMessages[line]['BODY[]']) if 'DevOps' in message.get_subject( ) or 'DevOps' in message.get_payload(): origem = message.get_address('from')[1] assunto = message.get_subject() data = message.get_decoded_header('date') insert_info = ("INSERT INTO MailsInfo (data, origem, assunto) \ VALUES ('{}','{}','{}')").format(origem, assunto, data) conn_sql(insert_info) except Exception as e: print(e)
def test_retrieves_implementation_socket(self) -> None: imap_client = imapclient.IMAPClient(host="get_socket://") self.addCleanup(imap_client.shutdown) self.assertEqual( phile.imapclient.get_socket(imap_client), imap_client._imap.sock, # pylint: disable=protected-access )
def check_and_run() : imap_conn = imapclient.IMAPClient (domain_name, ssl = True) print (imap_conn) try : print (imap_conn.login (emailaddress, password)) except : print ('Wrong username password combination! Please try again.') sys.exit() print (imap_conn.select_folder ('INBOX', readonly = False)) uids = imap_conn.gmail_search ('label:' + label + ' label:Inbox ' + emailaddress + ' subject:' + mysubject + ' label:unread') print (uids) messages = imap_conn.fetch (uids, ['BODY[]']) for x in messages.keys() : lstcomm = pyzmail.PyzMessage.factory (messages[x][b'BODY[]']) commands.append (lstcomm.text_part.get_payload().decode (lstcomm.text_part.charset)) print (imap_conn.logout()) twilioClient = TwilioRestClient (twilioSID, twilioAuthToken) for x in commands[::-1] : newfile = open ('commandstorun.py', 'w') newfile.write ('#! /usr/bin/python3\n') newfile.write (x) newfile.close() os.system ('chmod +x commandstorun.py') os.system ('./commandstorun.py') print ('Executed script :\n' + x) msg = twilioClient.messages.create (body = 'Your script has been executed! ' + x, from_ = sender, to = receiver) print (msg.status)