def imap_connection(self): if not self._imap_conn: if self._options.get('use_ssl', True): self._imap_conn = imaplib2.IMAP4_SSL(self._options['hostname']) else: self._imap_conn = imaplib2.IMAP4(self._options['hostname']) return self._imap_conn
def delete_remote_testfolders(cls, reponame=None): """Delete all INBOX.OLITEST* folders on the remote IMAP repository reponame: All on `reponame` or all IMAP-type repositories if None""" config = cls.get_default_config() if reponame: sections = ['Repository {0}'.format(reponame)] else: sections = [ r for r in config.sections() if r.startswith('Repository') ] sections = [ s for s in sections if config.get(s, 'Type').lower() == 'imap' ] for sec in sections: # Connect to each IMAP repo and delete all folders # matching the folderfilter setting. We only allow basic # settings and no fancy password getting here... # 1) connect and get dir listing host = config.get(sec, 'remotehost') user = config.get(sec, 'remoteuser') passwd = config.get(sec, 'remotepass') imapobj = imaplib.IMAP4(host) imapobj.login(user, passwd) res_t, data = imapobj.list() assert res_t == 'OK' dirs = [] for d in data: if d == '': continue if isinstance(d, tuple): # literal (unquoted) folder = '"%s"' % d[1].replace('"', '\\"') else: m = re.search(br''' [ ] # space (?P<dir> (?P<quote>"?) # starting quote ([^"]|\\")* # a non-quote or a backslashded quote (?P=quote))$ # ending quote ''', d, flags=re.VERBOSE) folder = m.group('dir').decode('utf-8') if not m.group('quote'): folder = '"%s"' % folder # folder = folder.replace(br'\"', b'"') # remove quoting dirs.append(folder) # 2) filter out those not starting with INBOX.OLItest and del... dirs = [ d for d in dirs if d.startswith('"INBOX.OLItest') or d.startswith('"INBOX/OLItest') ] for folder in dirs: res_t, data = imapobj.delete(folder) assert res_t == 'OK', "Folder deletion of {0} failed with error" \ ":\n{1} {2}".format(folder.decode('utf-8'), res_t, data) imapobj.logout()
def __init__(self, addr, timeout=60, ssl_ctx=None, factory=None): """Connect to an IMAP4 server.""" self.server_info = {} self._factory = factory self._last_noop = 0 self._in_iter = False if ssl_ctx is None and _use_ssl(addr): ssl_ctx = imaplib2.ssl_context() self.cn = imaplib2.IMAP4(addr, timeout, ssl_ctx) self._reset_mbox() if self.cn.state == 'auth': self._post_auth()
def _login(self): if self.imap_SSLEnable and self._imap_ssl_port > 0: self._imap = imaplib2.IMAP4_SSL(self._imap_server, port=self._imap_ssl_port) else: self._imap = imaplib2.IMAP4(self._imap_server, port=self._imap_port) try: t, d = self._imap.login(self._imap_user, self._imap_pass) if t == 'OK': return True else: return False except Exception, e: print e return False
def _connection_starttls(self): connection = imaplib.IMAP4(self.server, self.port) connection.starttls(create_default_context()) return connection
class Idler(threading.Thread): if Config.getboolean("imap", "ssl"): imap = imaplib2.IMAP4_SSL(Config.get("imap", "host")) else: imap = imaplib2.IMAP4(Config.get("imap", "host")) stopWaitingEvent = threading.Event() #Now, this stopWaitingEvent thing -- it really does make the whole thing work. Basically, #it holds a boolean value which is set and cleared using, oddly enough, the methods set() and #clear(). But, the good thing about it is that it has another method, wait(), which holds #execution until it has been set(). I cannot thank threading.Event() enough, I really couldn't #have done it without you! knownAboutMail = [] # will be a list of IDs of messages in the inbox killNow = False # stops execution of thread to allow propper closing of conns. """ Initialise (sorry, I'm from the UK) everything to get ready for PUSHed mail. """ def __init__(self, GMailUsername, GMailPassword): os.system('clear') debugMsg('DEBUG is ENABLED') debugMsg('__init__() entered') try: #establish connection to IMAP Server self.imap.LOGIN(GMailUsername, GMailPassword) self.imap.SELECT("INBOX") #get the IDs of all messages in the inbox and put in knowAboutMail typ, data = self.imap.SEARCH(None, 'ALL') self.knownAboutMail = data[0].split() #now run the inherited __init__ method to create thread threading.Thread.__init__(self) except: #Uh Oh, something went wrong print 'ERROR: IMAP Issue. It could be one (or more) of the following:' print '- The imaplib2.py file needs to be in the same directory as this file' print '- You\'re not connected to the internet' print '- Google\'s mail server(s) is/are down' print '- Your username and/or password is incorrect' sys.exit(1) debugMsg('__init__() exited') """ The method invoked when the thread id start()ed. Enter a loop executing waitForServer() untill kill()ed. waitForServer() can, and should, be continuously executed to be alerted of new mail. """ def run(self): debugMsg('run() entered') #loop until killNow is set by kill() method while not self.killNow: self.waitForServer() debugMsg('run() exited') """ Relay email contents to merlin via robocop. """ def robonotify(self, header, body): # Check for correct "From" address? uname = re.findall("(.+)@.+", header['To'])[0].split()[1] dsuff = Config.get("imap", "defsuffix") if dsuff: if uname[-len(dsuff):] == dsuff: uname = uname[:-len(dsuff)] else: self.forwardMail(uname, header, body) return tick = re.findall("events in tick (\d+)", body)[0] newfleets = re.findall("We have detected an open jumpgate from (.+), located at (\d{1,2}):(\d{1,2}):(\d{1,2}). " +\ "The fleet will approach our system in tick (\d+) and appears to have (\d+) visible ships.", body) recalls = re.findall( "The (.+) fleet from (\d{1,2}):(\d{1,2}):(\d{1,2}) has been recalled.", body) cons = len( re.findall( "Our construction team reports that .+ has been finished", body)) res = len( re.findall("Our scientists report that .+ has been finished", body)) # Wrap it up in a bow for line in newfleets: push("defcall", etype="new", uname=uname, tick=tick, name=line[0], x=line[1], y=line[2], z=line[3], eta=line[4], size=line[5]) for line in recalls: push("defcall", etype="rec", uname=uname, tick=tick, name=line[0], x=line[1], y=line[2], z=line[3]) if res + cons > 0: push("defcall", etype="fin", uname=uname, tick=tick, res=res, cons=cons) if len(newfleets) + len(recalls) + cons + res == 0: self.forwardMail(uname, header, body) """ Decide whether to forward mail. """ def forwardMail(self, uname, header, body): if not Config.getboolean("imap", "forwarding"): return body = "Original Message from %s\n\n" % (header['From']) + body user = User.load(uname) if user: addr = user.email else: addr = Config.get("imap", "bounce") body = "Bad username: %s\n\n" % (uname) + body if addr: self.send_email(header['Subject'], body, addr) """ Send an email using smtplib. """ def send_email(self, subject, message, addr): try: if (Config.get("smtp", "port") == "0"): smtp = SMTP("localhost") else: smtp = SMTP(Config.get("smtp", "host"), Config.get("smtp", "port")) if not ((Config.get("smtp", "host") == "localhost") or (Config.get("smtp", "host") == "127.0.0.1")): try: smtp.starttls() except SMTPException as e: raise SMSError("unable to shift connection into TLS: %s" % (str(e), )) try: smtp.login(Config.get("smtp", "user"), Config.get("smtp", "pass")) except SMTPException as e: raise SMSError("unable to authenticate: %s" % (str(e), )) try: smtp.sendmail( Config.get("smtp", "frommail"), addr, "To:%s\nFrom:%s\nSubject:%s\n%s\n" % (addr, "\"%s\" <%s>" % (Config.get("Alliance", "name"), Config.get("smtp", "frommail")), subject, message)) except SMTPSenderRefused as e: raise SMSError("sender refused: %s" % (str(e), )) except SMTPRecipientsRefused as e: raise SMSError("unable to send: %s" % (str(e), )) smtp.quit() except (socket.error, SSLError, SMTPException, SMSError) as e: return "Error sending message: %s" % (str(e), ) """ Name says it all really: get (just) the specified header fields from the server for the specified message ID. """ def getMessageHeaderFieldsById(self, id, fields_tuple): debugMsg('getMessageHeaderFieldsById() entered') #get the entire header typ, header = self.imap.FETCH(id, '(RFC822.HEADER)') #get individual lines headerlines = header[0][1].splitlines() #get the lines that start with the values in fields_tuple results = {} for field in fields_tuple: results[field] = '' for line in headerlines: if line.startswith(field): results[field] = line debugMsg('getMessageHeaderFieldsById() exited') return results #which is a dictionary containing the the requested fields """ The main def for displaying messages. It draws on getMessageHeaderFieldsById() and growlnotify() to do so. """ def showNewMailMessages(self): debugMsg('showNewMailMessages() entered') #get IDs of all UNSEEN messages typ, data = self.imap.SEARCH(None, 'UNSEEN') debugMsg('data - new mail IDs:') debugMsg(data, 0) for id in data[0].split(): if not id in self.knownAboutMail: #get From and Subject fields from header headerFields = self.getMessageHeaderFieldsById( id, ('From', 'To', 'Subject')) print self.imap.fetch(id, '(BODY[TEXT])')[1][0][1] debugMsg('headerFields dict. (from showNewMailMessage()):') debugMsg(headerFields, 0) #notify self.robonotify(headerFields, self.imap.fetch(id, '(BODY[TEXT])')[1][0][1]) #add this message to the list of known messages self.knownAboutMail.append(id) debugMsg('showNewMailMessages() exited') """ Called to stop the script. It stops the continuous while loop in run() and therefore stops the thread's execution. """ def kill(self): self.killNow = True # to stop while loop in run() self.timeout = True # keeps waitForServer() nice self.stopWaitingEvent.set( ) # to let wait() to return and let execution continue """ This is the block of code called by the run() method of the therad. It is what does all the waiting for new mail (well, and timeouts). """ def waitForServer(self): debugMsg('waitForServer() entered') #init self.newMail = False self.timeout = False self.IDLEArgs = '' self.stopWaitingEvent.clear() def _IDLECallback(args): self.IDLEArgs = args self.stopWaitingEvent.set() #_IDLECallack() is entered when the IMAP server responds to the IDLE command when new #mail is received. The self.stopWaitingEvent.set() allows the .wait() to return and #therefore the rest of waitForServer(). #attach callback function, and let server know it should tell us when new mail arrives self.imap.idle(timeout=60 * ServerTimeout, callback=_IDLECallback) #execution will stay here until either: # - a new message is received; or # - the timeout has happened # - we set the timout -- the RFC says the server has the right to forget about # us after 30 mins of inactivity (i.e. not communicating with server for 30 mins). # By sending the IDLE command every 29 mins, we won't be forgotten. # - Alternatively, the kill() method has been invoked. self.stopWaitingEvent.wait() #self.IDLEArgs has now been filled (if not kill()ed) if not self.killNow: # skips a chunk of code to sys.exit() more quickly. try: b = bool( self.IDLEArgs[0][1][0] == ('IDLE terminated (Success)')) except TypeError: b = False self.timeout = True if b: # This (above) is sent when either: there has been a timeout (server sends); or, there # is new mail. We have to check manually to see if there is new mail. typ, data = self.imap.SEARCH( None, 'UNSEEN') # like before, get UNSEEN message IDs debugMsg('Data: ') debugMsg(data, 0) #see if each ID is new, and, if it is, make newMail True for id in data[0].split(): if not id in self.knownAboutMail: self.newMail = self.newMail or True else: self.timeout = True # gets executed if there are UNSEEN messages that we have been notified of, # but we haven't yet read. In this case, it response was just a timeout. if data[0] == '': # no IDs, so it was a timeout (but no notified but UNSEEN mail) self.timeout = True #now there has either been a timeout or a new message -- Do something... if self.newMail: debugMsg('INFO: New Mail Received') self.showNewMailMessages() elif self.timeout: debugMsg('INFO: A Timeout Occurred') debugMsg('waitForServer() exited')
# Show raw IMAP data stream imaplib2.debug_func(debug) imaplib2.debug_level(4) # # IMAP4 connection example # # Create a new SSL context if USE_SSL is set to True ssl_ctx = imaplib2.ssl_context() if USE_SSL else None msg('Connecting...') with imaplib2.IMAP4(SERVER, timeout=15, ssl_ctx=ssl_ctx) as imap: msg('Server says hi: {}', imap.greeting) # Enable TLS if SSL wasn't used and the server supports it if not USE_SSL and imaplib2.ssl and 'STARTTLS' in imap.caps: msg('Enabling TLS...') imap.starttls(imaplib2.ssl_context()) # Send username and password msg('Authenticating...') imap.login(USERNAME, PASSWORD) # Enable data compression if 'COMPRESS=DEFLATE' in imap.caps: msg('Enabling compression...') imap.compress()
def cb(cb_arg_list): response, cb_arg, error = cb_arg_list typ, data = response if not data: return for field in data: if type(field) is not tuple: continue print('Message %s:\n%s\n' % (field[0].split()[0], field[1])) import imaplib2 M = imaplib2.IMAP4() M.LOGIN(input("input login"), input("input pass")) M.SELECT(readonly=True) typ, data = M.SEARCH(None, 'ALL') for num in data[0].split(): M.FETCH(num, '(RFC822)', callback=cb) M.CLOSE() M.LOGOUT()