コード例 #1
0
ファイル: main.py プロジェクト: dlazesz/syncimap
def connect_imap_and_sync(from_host,
                          to_host,
                          last_state,
                          state_config_filename,
                          idle_timeout=240):  # TODO wait more?
    with IMAPClient(from_host['host'], port=int(from_host['port'])) as from_server,\
            IMAPClient(to_host['host'], port=int(to_host['port'])) as to_server:
        from_server.login(from_host['username'], from_host['password'])
        to_server.login(to_host['username'], to_host['password'])
        # from_server.capabilities()
        from_server.select_folder('INBOX', readonly=True)
        # to_server.capabilities()
        to_server.select_folder('INBOX')
        while True:
            copy_emails(from_server, to_server, last_state,
                        to_host['target_label'], state_config_filename)
            responses = []
            while len(responses) == 0:
                """
                Note that IMAPClient does not handle low-level socket errors that can happen 
                when maintaining long-lived TCP connections.
                Users are advised to renew the IDLE command every 10 minutes to avoid the connection
                from being abruptly closed.
                """
                from_server.idle()  # Start IDLE mode
                responses = from_server.idle_check(
                    timeout=idle_timeout
                )  # Wait max idle_timeout seconds for response
                from_server.idle_done()  # Must finish idle to send Keepalive
                from_server.noop()  # Keepalive for source
                to_server.noop()  # Keepalive for target
コード例 #2
0
def watch(mbsyncrc, channel, queue):
    store = mbsyncrc.stores[mbsyncrc.channels[channel]["master"]]
    account = mbsyncrc.accounts[store["account"]]

    ssl_context = ssl.create_default_context()
    if account["ssl"]:
        imap_client = IMAPClient(host=account["host"], ssl=True)
    else:
        imap_client = IMAPClient(host=account["host"], ssl=False)
        imap_client.starttls(ssl_context)

    assert imap_client.has_capability("IDLE")
    imap_client.login(account["user"], account["password"])
    imap_client.select_folder("INBOX")
    imap_client.idle()

    last_connected = time.monotonic()

    while True:
        now = time.monotonic()
        if now - last_connected >= 13 * 60:
            imap_client.idle_done()
            imap_client.idle()
            last_connected = now

        responses = imap_client.idle_check(timeout=13 * 60)
        print("idle msgs for {}: {}".format(channel, responses), flush=True)
        if any("EXISTS" in r[1].decode() for r in responses):
            print("idle alarm queued for {}".format(channel), flush=True)
            queue.put_nowait(("idle", time.time()))
コード例 #3
0
 def get_imap_connectivity(self):
     """ Connect to imap server and close the connection """
     context = ssl.SSLContext(ssl.PROTOCOL_TLS)
     context.options |= ssl.OP_NO_SSLv2
     context.options |= ssl.OP_NO_SSLv3
     context.options |= ssl.OP_NO_TLSv1
     context.options |= ssl.OP_NO_TLSv1_1
     context.verify_mode = ssl.CERT_NONE
     try:
         if self.opt_use_ssl:
             self.server = IMAPClient(self.opt_imap_server,
                                      use_uid=True,
                                      ssl=True,
                                      ssl_context=context)
         else:
             self.server = IMAPClient(self.opt_imap_server,
                                      use_uid=True,
                                      ssl=False)
     except Exception as e:
         raise Exception("Error connecting to %s with exception %s" %
                         (self.opt_imap_server, str(e)))
     else:
         self.helper.log_debug(
             'get_imap_connectivity: successfully connected to %s' %
             self.opt_imap_server)
コード例 #4
0
    def connect(self):
        host = self.account.get_config("configured_mail_server")
        port = int(self.account.get_config("configured_mail_port"))
        security = int(self.account.get_config("configured_mail_security"))

        user = self.account.get_config("addr")
        pw = self.account.get_config("mail_pw")

        if security == const.DC_SOCKET_PLAIN:
            ssl_context = None
        else:
            ssl_context = ssl.create_default_context()

            # don't check if certificate hostname doesn't match target hostname
            ssl_context.check_hostname = False

            # don't check if the certificate is trusted by a certificate authority
            ssl_context.verify_mode = ssl.CERT_NONE

        if security == const.DC_SOCKET_STARTTLS:
            self.conn = IMAPClient(host, port, ssl=False)
            self.conn.starttls(ssl_context)
        elif security == const.DC_SOCKET_PLAIN:
            self.conn = IMAPClient(host, port, ssl=False)
        elif security == const.DC_SOCKET_SSL:
            self.conn = IMAPClient(host, port, ssl_context=ssl_context)
        self.conn.login(user, pw)

        self.select_folder("INBOX")
コード例 #5
0
ファイル: cuckooinbox.py プロジェクト: primmus/cuckooinbox
def main():
        
    def checkConfigs():
        '''check for config file and define variables'''
        config = os.path.join(CUCKOO_ROOT,"cuckooinbox","cuckooinbox.conf")
        if not os.path.exists(config):
            raise CuckooStartupError("Config file does not exist at path: %s" % config)
    
    checkConfigs()
    config = Config(cfg=os.path.join(CUCKOO_ROOT,"cuckooinbox","cuckooinbox.conf"))
    config = config.get('cuckooinbox')
    username = config['username']
    passwd = config['passwd']
    imap = config['imap']
    imap_ssl = config['imap_ssl']
    email_whitelist = config['email_whitelist']
    interval = config['interval']
    
    '''welcome screen'''
    print '\n\n'
    print '\t\t@\tsend your malware to %s !\n' % (username)
    welcome_message = '           _,\n         ((\')\n        /\'--)\n        | _.\'\n       / |`=\n      \'^\''
    print welcome_message

    '''thread main function'''        
    def analyze(message):
        request = CuckooRequest(message)
        request.fetch(message)
        request.sendReport()
    
    '''define imap connection'''
    server = IMAPClient(imap, use_uid=True, ssl=imap_ssl)
    
    '''connect, login'''
    server.login(username, passwd)
   
    while True:
        try:
            '''set retrieve folder'''
            select_info = server.select_folder('INBOX')
            '''search for new message from email whitelist'''
            for account in email_whitelist.split(','):
                messages = server.search('UNSEEN FROM "%s"' % account)
                '''analyze emails from one account at a time'''
                if messages:
                    for message in messages:
                        thread = threading.Thread( target = analyze, args = (message,))
			thread.daemon = True
                        thread.start()
            time.sleep(interval)
        except:
            '''reconnect to mail account'''
            server = IMAPClient(imap, use_uid=True, ssl=imap_ssl)
            server.login(username, passwd)
            pass
コード例 #6
0
 def gmail_search(self, query):
     """Search the gmail imap server using gmail queries"""
     self.client.logout()
     self.client = IMAPClient(self.IMAP_SERVER, use_uid=True, ssl=True)
     self._login()
     # Can use full gmail queries like 'has:attachment in:unread'
     messages = self.client.gmail_search(query)
     self.messages_for_this_session.append(messages)
     # We recreate a whole connection after querying gmail because
     # otherwise it caches our search results forever
     self.client.logout()
     self.client = IMAPClient(self.IMAP_SERVER, use_uid=True, ssl=True)
     self._login()
     return self.emails_from_messages(messages)
コード例 #7
0
def loop():
    server = IMAPClient(HOSTNAME, use_uid=True, ssl=True)
    server.login(USERNAME, PASSWORD)

    if DEBUG:
        socketio.emit('alert', 'Logging in as ' + USERNAME, Broadcast=True)
        select_info = server.select_folder(MAILBOX)
        socketio.emit('alert',
                      '%d messages in INBOX' % select_info[b'EXISTS'],
                      Broadcast=True)

    folder_status = server.folder_status(MAILBOX, 'UNSEEN')
    newmails = int(folder_status[b'UNSEEN'])

    if DEBUG:
        socketio.emit('alert',
                      'You have' + str(newmails) + 'new emails!',
                      Broadcast=True)

    if newmails > NEWMAIL_OFFSET:
        GPIO.output(GREEN_LED, True)
        GPIO.output(RED_LED, False)
    else:
        GPIO.output(GREEN_LED, False)
        GPIO.output(RED_LED, True)

    time.sleep(MAIL_CHECK_FREQ)
コード例 #8
0
ファイル: connection.py プロジェクト: C380/Kanmail
    def make_imap(self):
        server_string = (
            f'{self.config.username}@{self.config.host}:{self.config.port} '
            f'(ssl={self.config.ssl})')
        self.config.log('debug', f'Connecting to IMAP server: {server_string}')

        ssl_context = ssl.create_default_context()
        if self.config.ssl_verify_hostname is False:
            self.config.log('warning', 'Disabling SSL hostname verification!')
            ssl_context.check_hostname = False

        imap = IMAPClient(
            self.config.host,
            port=self.config.port,
            ssl=self.config.ssl,
            ssl_context=ssl_context,
            timeout=self.config.timeout,
            use_uid=True,
        )
        imap.login(self.config.username, self.config.password)
        imap.normalise_times = False

        if self._selected_folder:
            imap.select_folder(self._selected_folder)

        self._imap = imap
        self.config.log('info', f'Connected to IMAP server: {server_string}')
コード例 #9
0
 def login(self):
     try:
         context = ssl.create_default_context(cafile=certifi.where())
         # context.check_hostname = False
         # context.verify_mode = ssl.CERT_NONE
         mailbox = IMAPClient(
             self.source.host,
             port=self.source.port,
             use_uid=True,
             ssl=self.source.use_ssl,
             ssl_context=context)
         # mailbox.debug = 5
         capabilities = mailbox.capabilities()
         if b'STARTTLS' in capabilities:
             # Always use starttls if server supports it
             mailbox.starttls(context)
         if b'IDLE' in capabilities:
             self.can_push = True
         mailbox.login(self.source.username, self.source.password)
         mailbox.select_folder(self.source.folder)
         self.selected_folder = True
         self.mailbox = mailbox
     except IMAP4.abort as e:
         raise IrrecoverableError(e)
     except IMAP4.error as e:
         raise ClientError(e)
コード例 #10
0
ファイル: server.py プロジェクト: thomasi/Lost-Photos-Found
    def __init__(self, host, username, password, debug=False):
        """
        Server class __init__ which expects an IMAP host to connect to

        @param host: gmail's default server is fine: imap.gmail.com
        @param username: your gmail account (i.e. [email protected])
        @param password: we highly recommend you to use 2-factor auth here
        """

        if not host:
            raise Exception('Missing IMAP host parameter in your config')

        try:
            self._server = IMAPClient(host, use_uid=True, ssl=True)
        except:
            raise Exception('Could not successfully connect to the IMAP host')

        setattr(self._server, 'debug', debug)

        # mails index to avoid unnecessary redownloading
        index = '.index_%s' % (username)
        index = os.path.join(_app_folder(), index)
        self._index = shelve.open(index, writeback=True)

        # list of attachments hashes to avoid dupes
        hashes = '.hashes_%s' % (username)
        hashes = os.path.join(_app_folder(), hashes)
        self._hashes = shelve.open(hashes, writeback=True)

        self._username = username
        self._login(username, password)
コード例 #11
0
    def __init__(self,
                 username,
                 password='******',
                 host='localhost',
                 port=143,
                 *args,
                 **kwargs):
        super().__init__(username, *args, **kwargs)
        self.imap = IMAPClient(host, port, use_uid=True, ssl=False)
        res = self.imap.login(username, password)
        self.cursor.execute(
            "SELECT lowModSeq,highModSeq,highModSeqMailbox,highModSeqThread,highModSeqEmail FROM account LIMIT 1"
        )
        row = self.cursor.fetchone()
        self.lastfoldersync = 0
        if row:
            self.lowModSeq,
            self.highModSeq,
            self.highModSeqMailbox,
            self.highModSeqThread,
            self.highModSeqEmail = row
        else:
            self.lowModSeq = 0
            self.highModSeq = 1
            self.highModSeqMailbox = 1
            self.highModSeqThread = 1
            self.highModSeqEmail = 1

        # (imapname, readonly)
        self.selected_folder = (None, False)
        self.mailboxes = {}
        self.sync_mailboxes()
        self.messages = {}
コード例 #12
0
ファイル: imap.py プロジェクト: chrismckinnel/pmc
 def login(self, server, username, password, use_ssl=False, **kwargs):
     try:
         self.server = IMAPClient(server, use_uid=True, ssl=use_ssl)
         self.server.login(username, password)
     except Exception as e:
         return (False, e.message)
     return (True, 'Login Successful')
コード例 #13
0
ファイル: test-imap.py プロジェクト: andyrusinov/imap-tester
def main():
    username,password,servername = os.environ.get('username'), \
                                   os.environ.get('password'), \
                                   os.environ.get('server')

    ssl_context = ssl.create_default_context()
    if not os.environ.get(
            'insecure'
    ) is None:  # variable "insecure" is set, need to disable cert check
        ssl_context.check_hostname = False
        ssl_context.verify_mode = ssl.CERT_NONE

    # check variables
    if var_is_none(username, password, servername):
        print('ERROR: need to set username password and server vars:\n' + \
              'docker run --env username=\'account\' --env password=\'password\'' + \
              '--env server=\'server\' [--env insecure=yes] --rm -it andyrusinov/imap-tester\n' + \
       'optional var [insecure] drops SSL secure requirements\n' + \
              'Note: this script never saves the messages. All it does is downloading ' + \
              'them from INBOX, printing their size and dropping them (thus checking the connection)')
        exit()

    # connect
    with IMAPClient(servername, ssl_context=ssl_context) as server:
        server.login(username, password)
        folders = [f[-1] for f in server.list_sub_folders()]
        for folder in folders:
            process_folder(server, folder)

    print("Logging out")
コード例 #14
0
ファイル: generic.py プロジェクト: lukaszle/sync-engine
def create_imap_connection(host, port, ssl_required):
    """
    Return a connection to the IMAP server.
    The connection is encrypted if the specified port is the default IMAP
    SSL port (993) or the server supports STARTTLS.
    IFF neither condition is met and SSL is not required, an insecure connection
    is returned. Otherwise, an exception is raised.

    """
    use_ssl = port == 993

    # TODO: certificate pinning for well known sites
    context = create_default_context()
    conn = IMAPClient(host, port=port, use_uid=True,
                      ssl=use_ssl, ssl_context=context, timeout=120)

    if not use_ssl:
        # If STARTTLS is available, always use it. If it's not/ it fails, use
        # `ssl_required` to determine whether to fail or continue with
        # plaintext authentication.
        if conn.has_capability('STARTTLS'):
            try:
                conn.starttls(context)
            except Exception:
                if not ssl_required:
                    log.warning('STARTTLS supported but failed for SSL NOT '
                                'required authentication', exc_info=True)
                else:
                    raise
        elif ssl_required:
            raise SSLNotSupportedError('Required IMAP STARTTLS not supported.')

    return conn
コード例 #15
0
    def __connect(self):
        if self.__fix_weak_dh:
            context = ssl.SSLContext(
                ssl.PROTOCOL_TLSv1_2)  # Workaround for weak dh key
            context.set_ciphers('DEFAULT@SECLEVEL=1')
        else:
            context = ssl.SSLContext()

        try:
            if self.isDebug():
                self.print("Connecting to server {}".format(self.__server))
            self.__imap_client = IMAPClient(self.__server,
                                            use_uid=True,
                                            ssl=self.__ssl,
                                            ssl_context=context,
                                            timeout=1.0)
        except gaierror:
            self.error("Failed to connect to Mail Server")
        except ssl.SSLError:
            self.fatal("Failed to connect to Mail Server (TLS Error)")
        else:
            try:
                if self.isDebug():
                    self.print("Login as user {}".format(self.__user))
                self.__imap_client.login(self.__user, self.__password)
            except LoginError:
                self.error("Mail Server login failed")
            else:
                if self.isDebug():
                    self.print("Login successful")
                self.__healthy = True
                self.__imap_client.select_folder('INBOX', readonly=False)
コード例 #16
0
ファイル: oauth.py プロジェクト: EthanBlackburn/sync-engine
    def connect_account(self, email, pw, imap_endpoint, account_id=None):
        """Provide a connection to a IMAP account.

        Raises
        ------
        socket.error
            If we cannot connect to the IMAP host.
        IMAPClient.error
            If the credentials are invalid.
        """
        host, port = imap_endpoint
        try:
            conn = IMAPClient(host, port=port, use_uid=True, ssl=True)
        except IMAPClient.AbortError as e:
            log.error('account_connect_failed',
                      account_id=account_id,
                      email=email,
                      host=host,
                      port=port,
                      error="[ALERT] Can't connect to host - may be transient")
            raise TransientConnectionError(str(e))
        except (IMAPClient.Error, gaierror, socket_error) as e:
            log.error('account_connect_failed',
                      account_id=account_id,
                      email=email,
                      host=host,
                      port=port,
                      error='[ALERT] (Failure): {0}'.format(str(e)))
            raise ConnectionError(str(e))

        conn.debug = False
        try:
            conn.oauth2_login(email, pw)
        except IMAPClient.AbortError as e:
            log.error('account_verify_failed',
                      account_id=account_id,
                      email=email,
                      host=host,
                      port=port,
                      error="[ALERT] Can't connect to host - may be transient")
            raise TransientConnectionError(str(e))
        except IMAPClient.Error as e:
            log.error('IMAP Login error during connection. '
                      'Account: {}, error: {}'.format(email, e),
                      account_id=account_id)
            if (str(e) == '[ALERT] Invalid credentials (Failure)'
                    or str(e).startswith('[AUTHENTICATIONFAILED]')):
                raise ValidationError(str(e))
            else:
                raise ConnectionError(str(e))
        except SSLError as e:
            log.error('account_verify_failed',
                      account_id=account_id,
                      email=email,
                      host=host,
                      port=port,
                      error='[ALERT] (Failure) SSL Connection error')
            raise ConnectionError(str(e))

        return conn
コード例 #17
0
ファイル: bot.py プロジェクト: ZeroBone/MailNotifierBot
    def get_emails(self):

        with IMAPClient(self.host, ssl=self.ssl) as server:

            try:
                server.login(self.login, self.password)
            except LoginError:
                logger.error("Could not authenticate.")
                return

            server.select_folder(self.folder, readonly=self.read_only)

            mails = server.search(self.criteria)

            for uid, message_data in server.fetch(mails, "RFC822").items():

                if uid <= self.last_uid:
                    continue

                try:
                    mail = mailparser.parse_from_bytes(message_data[b"RFC822"])
                except TypeError:
                    pass
                else:
                    yield mail, uid
コード例 #18
0
def do_worker_qq(smtp_account, smtp_password, smtp_list):
    # 通过一下方式连接smtp服务器,没有考虑异常情况,详细请参考官方文档
    server = IMAPClient(GLB_IMAP_HOSTNAME, ssl= True)
    try:
        server.login(smtp_account, smtp_password)
        server.select_folder('INBOX')

        year, mouth, day = glb_p_date.split('-')
        date = datetime.date(int(year), int(mouth), int(day))
        date2 = date - datetime.timedelta(days=1)
        result = server.search(['UNSEEN', 'SINCE', date2])
        msgdict = server.fetch(result, ['BODY.PEEK[]'] )
        msgtuple=sorted(msgdict.items(), key=lambda e:e[0], reverse=True)

        log_ids = []
        for message_id, message in msgtuple:
            msg_content = message['BODY[]']
            for log_id, mail_from, mail_to in smtp_list:
                if log_id in log_ids: continue
                error_type, return_said = do_email(msg_content, mail_to)
                if error_type is not None:
                    log_ids.append(log_id)
                    do_worker_imap_update(log_id, mail_to, return_said, error_type)
                    server.add_flags(message_id, '\\seen')
    finally:
        server.logout()
    return
コード例 #19
0
    def update(self, _reuse_imap=None) -> List[int]:
        new_msgs = []
        if _reuse_imap is None:
            imap = IMAPClient(host='imap.ietf.org', ssl=False, use_uid=True)
            imap.login("anonymous", "anonymous")
        else:
            imap = _reuse_imap
        imap.select_folder("Shared Folders/" + self._list_name, readonly=True)

        msg_list  = imap.search()
        msg_fetch = []

        for msg_id, msg in imap.fetch(msg_list, "RFC822.SIZE").items():
            cache_file = Path(self._cache_folder, F"{msg_id:06d}.msg")
            if not cache_file.exists():
                msg_fetch.append(msg_id)
            else:
                file_size = cache_file.stat().st_size
                imap_size = msg[b"RFC822.SIZE"]
                if file_size != imap_size:
                    self.log.warn(F"message size mismatch: {self._list_name}/{msg_id:06d}.msg ({file_size} != {imap_size})")
                    cache_file.unlink()
                    msg_fetch.append(msg_id)

        if len(msg_fetch) > 0:
            aa_cache     = Path(self._cache_folder, "aa-cache.json")
            aa_cache_tmp = Path(self._cache_folder, "aa-cache.json.tmp")
            aa_cache.unlink()

            for msg_id, msg in imap.fetch(msg_fetch, "RFC822").items():
                cache_file = Path(self._cache_folder, F"{msg_id:06d}.msg")
                fetch_file = Path(self._cache_folder, F"{msg_id:06d}.msg.download")
                if not cache_file.exists():
                    with open(fetch_file, "wb") as outf:
                        outf.write(msg[b"RFC822"])
                    fetch_file.rename(cache_file)

                    e = email.message_from_bytes(msg[b"RFC822"])
                    if e["Archived-At"] is not None:
                        list_name, msg_hash = _parse_archive_url(e["Archived-At"])
                        self._archive_urls[msg_hash] = msg_id
                    self._num_messages += 1
                    new_msgs.append(msg_id)

                    self._msg_metadata[msg_id] = {}
                    for helper in self._helpers:
                        self.log.info(F"{helper.name}: scan message {self._list_name}/{msg_id:06} for metadata")
                        self._msg_metadata[msg_id][helper.name] = helper.scan_message(e)

            with open(aa_cache_tmp, "w") as aa_cache_file:
                json.dump(self._archive_urls, aa_cache_file)
            aa_cache_tmp.rename(aa_cache)

        self.serialise_metadata()

        imap.unselect_folder()
        if _reuse_imap is None:
            imap.logout()
        self._last_updated = datetime.now()
        return new_msgs
コード例 #20
0
def debug(account):
    c = ACCOUNTS[account]
    if 'pass_cmd' in c:
        c['pass'] = check_output([c['pass_cmd']], shell=True).strip()
    client = IMAPClient(c['host'], use_uid=True, ssl=c['ssl'])
    client.login(c['user'], c['pass'])
    print(client.capabilities())
コード例 #21
0
def main():
    global g_next_UID
    initialize()
    server = IMAPClient(HOST)
    server.login(USERNAME, PASSWORD)
    inbox_folder = server.select_folder('INBOX')
    g_next_UID = inbox_folder['UIDNEXT']

    # Start IDLE mode
    server.idle()
    print(
        "Connection is now in IDLE mode, send yourself an email or quit with ^c"
    )

    while True:
        try:
            responses = server.idle_check(timeout=TIMEOUT)
            #print("Server sent:", responses if responses else "nothing")
            if responses:
                print('Server len(' + str(len(responses)) + ")->" +
                      ' '.join(str(x) for x in responses))
                for iR in responses:
                    if (iR[1] == 'EXISTS'):
                        mark_next_avail_server()
            else:
                print('...')
        except KeyboardInterrupt:
            break

    server.idle_done()
    print("\nIDLE mode done")
    server.logout()
コード例 #22
0
ファイル: main.py プロジェクト: akvamalin/L
def handler(event, context):
    ensure_env_set(env_vars)

    env_imap_server = environ.get(env_vars['imap_server'])
    env_user_name = environ.get(env_vars['user'])
    env_user_password = environ.get(env_vars['pass'])
    env_user_id = int(environ.get(env_vars['user_id']))
    env_telegram_token = environ.get(env_vars['token'])

    with IMAPClient(env_imap_server, use_uid=True) as client:
        client.login(env_user_name, env_user_password)
        client.select_folder('INBOX')
        print(f'Login for {env_user_name} is successful.')

        unread_messages = client.search([u'UNSEEN'])

        print(f'{len(unread_messages)} unread messages found.')

        bot = Bot(token=env_telegram_token)
        bot_info = bot.get_me()
        print(f'Started bot {bot_info.id} {bot_info.username}')

        chat_id = resolve_chat_id_for_user(env_user_id, bot.get_updates())
        bot.send_message(chat_id=chat_id,
                         text="{} unread messages found.".format(
                             len(unread_messages)))

        print('Done.')
コード例 #23
0
ファイル: watchdog.py プロジェクト: Linksfraktion/briefkasten
def fetch_test_submissions(previous_history, config):
    """ fetch emails from IMAP server using the given configuration
        each email is parsed to see whether it matches a submission
        if so, its token is extracted and checked against the given
        history.
        if found, the email is deleted from the server and the entry
        is removed from the history.
        any entries left in the history are returned
    """
    server = IMAPClient(config['imap_host'], use_uid=True, ssl=True)
    server.login(config['imap_user'], config['imap_passwd'])
    server.select_folder('INBOX')
    history = previous_history.copy()
    candidates = server.fetch(
        server.search(criteria=['NOT DELETED', 'SUBJECT "Drop ID"']),
        ['BODY[HEADER.FIELDS (SUBJECT)]'])
    for imap_id, message in candidates.items():
        subject = message.get('BODY[HEADER.FIELDS (SUBJECT)]', 'Subject: ')
        try:
            drop_id = find_drop_id.findall(subject)[0]
        except IndexError:
            # ignore emails that are not test submissions
            continue
        print "Found submission '%s'" % drop_id
        server.delete_messages([imap_id])
        try:
            del history[drop_id]
        except KeyError:
            pass  # TODO: log this?
    server.logout()
    return history
コード例 #24
0
ファイル: mail.py プロジェクト: Data4ITBV/hermes
    def reset(self):

        try:
            self._client.logout()
        except IMAPClientError as e:
            pass
        except OSError as e:
            pass

        try:
            self._client = IMAPClient(
                host=self._hote_imap,
                port=993 if self._use_secure_socket else 143,
                ssl=self._use_secure_socket,
                ssl_context=self._ssl_context)
            self._client.login(
                self._nom_utilisateur,
                Session.UNIVERSELLE.retranscrire(self._mot_de_passe))
        except IMAPClientError as e:
            logger.error(
                "Une erreur IMAP critique est survenue lors de la reconnexion. {msg_err}",
                msg_err=str(e))
            self._echec = True
            return

        self._echec = False
コード例 #25
0
ファイル: main.py プロジェクト: ModischFabrications/ReMailer
def connect_imap(logger, mail: str, password: str) -> IMAPClient:
    """
    prepare the connection to receive mails

    :param logger: logging object
    :param mail: string for mail, e.g.
    :param password: string for password (not printed to log)
    :return: connection object
    """

    host = mail.split("@")[1]
    try:
        imap_domain = imap_provider[host]
    except KeyError:
        logger.error(f"IMAP-Provider {host} is unknown, exiting")
        # TODO try imap.XX before giving up
        exit(2)

    logger.info(f"Connecting to {imap_domain}")
    imap_obj = IMAPClient(imap_domain, ssl=True)

    logger.info(f"Logging in")

    response = imap_obj.login(mail, password)
    logger.debug(response)

    logger.info(f"Successful. Ready to receive")

    return imap_obj
コード例 #26
0
def cleanup():
    """EmailListener test suite teardown, moves the test email to the Trash."""

    # Let the other fixtures and the test run
    yield

    # Create an email listener
    email = os.environ['EL_EMAIL']
    app_password = os.environ['EL_APW']
    server = IMAPClient('imap.gmail.com')
    server.login(email, app_password)
    server.select_folder("email_listener", readonly=False)
    messages = server.search("UNSEEN")
    for uid, message_data in server.fetch(messages, 'RFC822').items():
        print("uid: {}".format(uid))
        server.set_gmail_labels(uid, "\\Trash")
    server.logout()

    # Delete any downloaded attachments
    download_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                "attachments")
    for file in os.listdir(download_dir):
        file_ext = file.split('.')[-1]
        if (file_ext == "txt"):
            full_path = os.path.join(download_dir, file)
            os.remove(full_path)
コード例 #27
0
def _idle_client(account, box, state):
    wait_connect()
    c = ACCOUNTS[account]
    if 'pass_cmd' in c:
        c['pass'] = check_output([c['pass_cmd']], shell=True).strip()
    client = IMAPClient(c['host'], use_uid=True, ssl=c['ssl'])
    client.login(c['user'], c['pass'])
    try:
        client.select_folder(box)
    except:
        print(Style.BRIGHT + Fore.RED +
              "unable to select folder {}".format(box) + Fore.RESET +
              Style.RESET_ALL)
        return
    client.idle()

    print("connected, {}: {}".format(account, box))
    while not state['got_signal']:
        for m in client.idle_check(timeout=30):
            if m != (b'OK', b'Still here'):
                print(
                    Style.BRIGHT + Fore.GREEN,
                    "event: {}, {}, {}".format(account, box, m) + Fore.RESET +
                    Style.RESET_ALL)
                sync(c['local'], box)
        sleep(1)
    client.logout()
コード例 #28
0
    def connect(self) -> bool:
        """
        Connect and login to the remote IMAP server.

        Returns:
            (bool): True if successful, otherwise False
        """
        mailserver = os.environ.get('mailserver')
        imapport = os.environ.get('imapport')
        mailssl = os.environ.get('mailssl')
        try:
            self.server = IMAPClient(
                mailserver,
                port=imapport,
                ssl=mailssl,
                use_uid=True
            )
            username = os.environ.get('mail_username')
            password = os.environ.get('mail_password')
            self.logger.debug(f"Username: {username}, Password: {password}")
            self.server.login(username, password)
        except ConnectionRefusedError as e:
            self.logger.fatal(f"Connection to {mailserver}:{imapport} was refused: {str(e)}")
            return False
        except Exception as e:
            self.logger.fatal(f"Connection to {mailserver}:{imapport} was refused: {str(e)}")
            return False

        return True
コード例 #29
0
ファイル: imapauth.py プロジェクト: dadosch/mumble_auth_imap
        def authenticate(self, name, pw, certlist, certhash, strong, current = None):
            """
            This function is called to authenticate a user
            """
            
            # Search for the user in the database
            FALL_THROUGH = -2
            AUTH_REFUSED = -1
            
            if name == 'SuperUser':
                debug('Forced fall through for SuperUser')
                return (FALL_THROUGH, None, None)
            

            try:
                with IMAPClient(host=cfg.imap.host, ssl_context=ssl_context) as client:
                    client.login(name, pw)
            except IMAPClient.Error as e:
                info('Fall through for unknown user "%s" or connection problem', name)
                return (AUTH_REFUSED, None, None)
            
            # As IMAP hasn't got such thing as a USERID, we use the given name to calculate a hash 
	    # TODO this might be highly insecure when two mails have coindently the same hash (note that we are cutting the integer off as otherwise we would get an error from mumble)
            uid = hashString(name)
            info('User authenticated: "%s", UID: %s', name, str(uid))
            return (uid, name, [])
コード例 #30
0
    def _connect_and_fetch(self):
        self._server = IMAPClient(self.host, timeout=self.socket_timeout)
        self._server.login(self.username, self.password)

        self._server.select_folder('INBOX')

        self._fetch_unseen()