def create_default_context(): """ Return a backports.ssl.SSLContext object configured with sensible default settings. This was adapted from imapclient.create_default_context to allow all ciphers and disable certificate verification. """ # adapted from Python 3.4's ssl.create_default_context context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) # do not verify that certificate is signed nor that the # certificate matches the hostname context.verify_mode = ssl.CERT_NONE context.check_hostname = False # SSLv2 considered harmful. context.options |= _ossl.OP_NO_SSLv2 # SSLv3 has problematic security and is only required for really old # clients such as IE6 on Windows XP context.options |= _ossl.OP_NO_SSLv3 # disable compression to prevent CRIME attacks (OpenSSL 1.0+) context.options |= getattr(_ossl, "OP_NO_COMPRESSION", 0) # Prefer the server's ciphers by default so that we get stronger # encryption context.options |= getattr(_ossl, "OP_CIPHER_SERVER_PREFERENCE", 0) # Use single use keys in order to improve forward secrecy context.options |= getattr(_ossl, "OP_SINGLE_DH_USE", 0) context.options |= getattr(_ossl, "OP_SINGLE_ECDH_USE", 0) return context
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 emailTorrent(): logging.debug('Starting IMAP connection') dayAgo = datetime.datetime.now() - datetime.timedelta(days=1) timeString = dayAgo.strftime('%d-%b-%Y') context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True, ssl_context=context) imapObj.login('*****@*****.**', 'password') imapObj.select_folder('INBOX', readonly=False) UIDs = imapObj.search('SINCE ' + timeString) logging.debug('Number of new messages: ' + str(len(UIDs))) rawMessages = imapObj.fetch(UIDs, ['BODY[]']) for uid in UIDs: message = pyzmail.PyzMessage.factory(rawMessages[uid][b'BODY[]']) if message.text_part != None: msgText = message.text_part.get_payload().decode( message.text_part.charset) if '4x567' in message.get_subject(): logging.debug('Message with password detected') torrentProcess = subprocess.Popen( ['C:\Program Files (x86)\BitLord\BitLord.exe', msgText]) imapObj.delete_messages(uid) sendMail('started: ' + msgText) logging.debug('Message with start info sent') torrentProcess.wait() sendMail('finished: ' + msgText) logging.debug('Message with end info sent') imapObj.logout()
def gmail_connection(self): context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE context.check_hostname = False self.conn = imapclient.IMAPClient('imap.googlemail.com', ssl=True, ssl_context=context) return self.form_csv()
def login(email, password): '''Authorize and login to gmail account.''' context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True, ssl_context=context) imapObj.login(email, password) imapObj.select_folder('INBOX', readonly=True) return imapObj
def ssl_connection(self): context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE context.check_hostname = False self.conn = imapclient.IMAPClient(self.server, port=self.port, ssl=True, ssl_context=context) return self.form_csv()
def moveEmailTwo(): HOST = 'imap.gmail.com' un = config['Main']['Email'] pw = config['Main']['Password'] context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) server = IMAPClient(HOST, use_uid=True, ssl=True, ssl_context=context) server.login(un, pw) select_info = server.select_folder(EMAIL_FOLDER) print('%d messages in INBOX' % select_info[b'EXISTS']) messages = server.search(['NOT', 'DELETED']) print("%d messages that aren't deleted" % len(messages)) print() print("Messages:") response = server.fetch(messages, ['FLAGS', 'RFC822.SIZE']) for msgid, data in response.items(): print(' ID %d: %d bytes, flags=%s' % (msgid, data[b'RFC822.SIZE'], data[b'FLAGS']))
import os import pyautogui from pywinauto.findwindows import find_window from pywinauto.win32functions import SetForegroundWindow from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage # email_username = input("Username? ") # email_password = input("Password? ") email_username = lines[2][0:-1] email_password = lines[3][0:-1] imaplib._MAXLINE = 10000000 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True, ssl_context=context) imapObj.login(email_username, email_password) smtpObj = smtplib.SMTP('smtp.gmail.com', 587) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(email_username, email_password) def check_inbox(imap_object): imap_object.select_folder('INBOX', readonly=False) UIDs = imapObj.search(['ALL', 'UNSEEN']) raw_messages = imap_object.fetch(UIDs, ['BODY[]']) return raw_messages, UIDs
def create_default_context(cafile=None, capath=None, cadata=None): """Return a backports.ssl.SSLContext object configured with sensible default settings. The optional *cafile* argument is path to a file of concatenated CA certificates in PEM format. The optional *capath* argument is a path to a directory containing several CA certificates in PEM format, following an OpenSSL specific layout. The optional *cadata* argument is either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates. If *cafile*, *capath* and *cadata* are all None then system-installed CA certificates will be loaded (if available). """ # adapted from Python 3.4's ssl.create_default_context context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) # require certificate that matches the host name. context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True # SSLv2 considered harmful. context.options |= _ossl.OP_NO_SSLv2 # SSLv3 has problematic security and is only required for really old # clients such as IE6 on Windows XP context.options |= _ossl.OP_NO_SSLv3 # disable compression to prevent CRIME attacks (OpenSSL 1.0+) context.options |= getattr(_ossl, "OP_NO_COMPRESSION", 0) # Prefer the server's ciphers by default so that we get stronger # encryption context.options |= getattr(_ossl, "OP_CIPHER_SERVER_PREFERENCE", 0) # Use single use keys in order to improve forward secrecy context.options |= getattr(_ossl, "OP_SINGLE_DH_USE", 0) context.options |= getattr(_ossl, "OP_SINGLE_ECDH_USE", 0) # disallow ciphers with known vulnerabilities # TODO: backports.ssl.SSLContext is missing set_ciphers context._ctx.set_cipher_list(_RESTRICTED_SERVER_CIPHERS) if cafile or capath or cadata: context.load_verify_locations(cafile, capath, cadata) elif context.verify_mode != ssl.CERT_NONE: # no explicit cafile, capath or cadata but the verify mode is # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system # root CA certificates for the given purpose. This may fail silently. if sys.platform == "win32": certs = bytearray() for storename in ("CA", "ROOT"): for cert, encoding, trust in enum_certificates(storename): # CA certs are never PKCS#7 encoded if encoding == "x509_asn": if trust is True or Purpose.SERVER_AUTH in trust: certs.extend(cert) if certs: context.load_verify_locations(cadata=certs) else: context.set_default_verify_paths() return context
HOST = 'imap.gmail.com' user = '******' import imapclient from backports import ssl import getpass if __name__ == '__main__': print('CmdMAIL') print('-------------------------') print('Connecting') context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE context.check_hostname = False server = imapclient.IMAPClient(HOST, use_uid=True, ssl=True, ssl_context=context) print('Signing in') server.login(user, getpass.getpass()) print('Done!') print('Selecting folder') inbox = server.select_folder('INBOX') messages = server.search(['NOT', 'DELETED']) print('%d messages in INBOX' % len(messages))
class Connection: context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.verify_mode = ssl.CERT_NONE context.check_hostname = False connection = {} imap_address = '' def __init__(self, imap_address): self.imap_address = imap_address def connect(self): print('') try: self.connection = imapclient.IMAPClient(self.imap_address, ssl=True, ssl_context=self.context) except Exception as err: print(err) print('Connected to your email IMAP server ({0}).'.format( self.imap_address)) def disconnect(self): print('') print('Logging out.\n') self.connection.logout() def login(self): print('') print('Let\'s login... ') try: email = input('Email > ') password = getpass.getpass('Password > ') self.connection.login(email, password) except Exception as err: print(err) exit(1) print('You\'re connected successfully.') def select_folder(self, folder_name): print('') try: self.connection.select_folder(folder_name, readonly=True) except Exception as err: print(err) exit(1) print('Selected Folder: {0}'.format(folder_name)) def fetch_emails_by_uid(self, UIDs): rawMessages = self.connection.fetch(UIDs, ['RFC822']) # raw messages get returned in a byte format, I need to convert them to strings to parse through them a little bit easier print('') print('Converting Raw Messages ...') return self.convert(rawMessages) def list_subjects(self, convertedMessages): print('Found {0} Messages\n'.format(len(convertedMessages))) print(bcolors.OKBLUE + '{:10}{:50}'.format('UID', 'Subject') + bcolors.ENDC) for uid in convertedMessages: parsedMessage = email.message_from_string( convertedMessages[uid]['RFC822']) print('{:10}{:.30s}...'.format(str(uid), parsedMessage['Subject'])) # BeautifulSoup(''.join(str(v) for v in parsedMessage.get_payload()), 'html.parser') def convert(self, data): if isinstance(data, bytes): return data.decode('ascii') if isinstance(data, dict): return dict(map(self.convert, data.items())) if isinstance(data, tuple): return map(self.convert, data) return data
def readAll(): try: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) server = imapclient.IMAPClient(smtp, ssl=True, ssl_context=context) server.login(address, password) server.select_folder('INBOX', readonly=True) # Read from Inbox UID = server.search(['SEEN']) x = (len(UID) - 10) # Only print 10 emails at a time i = len(UID) if (i > 0): # Print number of emails found print('\nYou have ' + str(len(UID)) + ' emails being queried\n') print( '-----------------------------------------------------------------------------------------------------------------------------------------------------------------------' ) if (i == 0): print('\nYou have no new mail\n') print( '-----------------------------------------------------------------------------------------------------------------------------------------------------------------------' ) while ((i > x) and (i > 0)): i -= 1 var = UID[i] # If an email is found, parse through it rawMessage = server.fetch(UID[i], ['BODY[]', 'FLAGS']) message = pyzmail.PyzMessage.factory(rawMessage[var][b'BODY[]']) subject = message.get_subject() sender = message.get_address('from') receiver = message.get_address('to') if (message.text_part == None): print('\n\nError loading UID [' + str(i) + ']\n\nText type not supported\n\n') print( '\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------' ) continue if (message.text_part.charset == None): print('\n\nError loading UID [' + str(i) + ']\n\nText type not supported\n\n') print( '\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------' ) continue print('\n\n[' + str(i) + ']') # Print the parsed email's body print('SUBJECT: ' + str(subject)) print('SENT BY: ' + str(sender)) os.environ["LANG"] = "en_US.UTF-8" message.text_part != None os.environ["LANG"] = "en_US.UTF-8" print('\nMESSAGE: \n' + str(message.text_part.get_payload().decode( message.text_part.charset))) print( '\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------' ) if (i == x): print('Enter "+" to read more emails') print( 'Enter "exit" to exit') # Prompt user to load more emails prompt = input() if prompt == '+': x -= 10 elif prompt == 'stop': x += 100 except Exception as e: print('An error occured: ' + str(e)) print( '\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------' )
print "Enter notifications user password:"******"Enter digest user password:"******"use_uid": True, "ssl": options.notifications_ssl} if not old_imapclient and options.notifications_cert_check_skip: notifications_context = None notifications_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) notifications_context.check_hostname = False notifications_context.verify_mode = ssl.CERT_NONE kwargs["ssl_context"] = notifications_context try: notification_folder = IMAPClient(options.notifications_imap, **kwargs) except gaierror: print "CAN'T FIND IMAP SERVER" exit(10) try: notification_folder.login(options.notifications_user, options.notifications_pw) except: time.sleep(5) notification_folder = IMAPClient(options.notifications_imap, **kwargs)