コード例 #1
0
ファイル: backends.py プロジェクト: aldur/django-imapauth
    def authenticate(self, username=None, password=None):
        try:
            # Check if this user is valid on the mail server
            if IMAPAUTH_PORT:
                c = IMAP4_SSL(IMAPAUTH_HOST, IMAPAUTH_PORT)
            else:
                c = IMAP4_SSL(IMAPAUTH_HOST)
        except ssl.SSLError:  # remote server doesn't speak SSL
            if IMAPAUTH_PORT:
                c = IMAP4(IMAPAUTH_HOST, IMAPAUTH_PORT)
            else:
                c = IMAP4(IMAPAUTH_HOST)
        finally:
            try:
                c.login(username, password)
                c.logout()
            except:
                return None

        try:
            # Check if the user exists in Django's local database
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # Create a user in Django's local database
            user = User.objects.create_user(username,
                                            password='******')
        return user
コード例 #2
0
    def __init__(self, username, password):

        self.imap = IMAP4_SSL(GMAIL_IMAP_HOST, GMAIL_IMAP_PORT)
        code, _ = self.imap.login(username, password)
        if code != 'OK':
            raise Exception('gmail login failure')
        self.imap.select('INBOX')
コード例 #3
0
    def imap_callback_message(self):
        username = self.config['IMAP_USERNAME']
        password = self.config['IMAP_PASSWORD']

        try:
            imap = IMAP4_SSL(self.config['IMAP_SERVER'])
            imap.login(username, password)
            imap.select()

            new = imap.search(None, 'UNSEEN')[1][0].decode('utf-8')
            if new:
                for emailid in new.split(' '):
                    email = imap.fetch(emailid, '(RFC822)')[1][0][1]
                    email = email.decode('utf-8')
                    email = Parser().parsestr(email)

                    sender = email['From']
                    subject = email['Subject']

                    if self.config['MENTION_DELIM'] in subject:
                        mention, text = subject.split(': ', 1)
                        self.relay_message(mention, sender, text)

            imap.close()
            imap.logout()
        except IMAP4.error as err:
            logging.debug('IMAP4.error: {}'.format(err))
コード例 #4
0
    def open_mailbox(self, **kwargs):
        """Open IMAP email client session to given ``host`` with given ``user`` and ``password``.

        Arguments:
        - ``host``: The IMAP host server. (Default None)
        - ``is_secure``: An indicator flag to connect to IMAP host securely or not. (Default True)
        - ``password``: The plaintext password to be use to authenticate mailbox on given ``host``.
        - ``port``: The IMAP port number. (Default None)
        - ``user``: The username to be use to authenticate mailbox on given ``host``.
        - ``folder``: The email folder to read from. (Default INBOX)

        Examples:
        | Open Mailbox | host=HOST | user=USER | password=SECRET |
        | Open Mailbox | host=HOST | user=USER | password=SECRET | is_secure=False |
        | Open Mailbox | host=HOST | user=USER | password=SECRET | port=8000 |
        | Open Mailbox | host=HOST | user=USER | password=SECRET | folder=Drafts
        """
        host = kwargs.pop('host', kwargs.pop('server', None))
        is_secure = kwargs.pop('is_secure', 'True') == 'True'
        port = int(kwargs.pop('port', self.PORT_SECURE if is_secure else self.PORT))
        folder = '"%s"' % str(kwargs.pop('folder', self.FOLDER))
        self._imap = IMAP4_SSL(host, port) if is_secure else IMAP4(host, port)
        self._imap.login(kwargs.pop('user', None), kwargs.pop('password', None))
        self._imap.select(folder)
        self._init_multipart_walk()
コード例 #5
0
ファイル: ImapSmtp.py プロジェクト: mdp/rpaframework
    def authorize_imap(self,
                       account: str = None,
                       password: str = None,
                       imap_server: str = None) -> None:
        """Authorize to IMAP server.

        Can be called without giving any parameters if library
        has been initialized with necessary information and/or
        keyword ``set_credentials`` has been used.

        :param account: IMAP account name, defaults to None
        :param password: IMAP account password, defaults to None
        :param smtp_server: IMAP server address, defaults to None
        """
        if account is None and password is None:
            account = self.account
            password = self.password
        if imap_server is None:
            imap_server = self.imap_server
        if imap_server and account and password:
            self.imap_conn = IMAP4_SSL(imap_server)
            self.imap_conn.login(account, password)
            self.imap_conn.select("inbox")
        else:
            self.logger.warning(
                "Server address, account and password are needed for "
                "authentication with IMAP")
        if self.imap_conn is None:
            self.logger.warning("Not able to establish IMAP connection")
コード例 #6
0
    def _call_imap_server(self):
        try:
            # connect to IMAP with SSL
            self.mailbox = IMAP4_SSL(ConfigService.get('EMAIL_SVC_IMAP'))
            self.mailbox.login(ConfigService.get('EMAIL_ACCOUNT'), ConfigService.get('EMAIL_PASSWD'))
        except Exception as e:
            print("FATAL : login to mailbox failed", e)
            exit(1)

        # change folder
        rv, data = self.mailbox.select(ConfigService.get('EMAIL_FOLDER'))
        if rv == 'OK':
            print("> Opening mailbox...")
            # do some stuff
            process_mailbox(self.mailbox)
            print("> Done.")
        else:
            print("ERROR: Unable to open mailbox", rv)
            self.mailbox.close()
            self.mailbox.logout()
            exit(1)

        # exit mailbox
        self.mailbox.close()
        self.mailbox.logout()

        # sleep for 10 minutes
        print("~ waiting 10 min")
        sleep(600)
コード例 #7
0
ファイル: email.py プロジェクト: scaroline/IssuesMonitoring
def fetch_new_emails(host=HOST, username=USERNAME, password=PASSWORD):
    debug("Checking for unread e-mails.")
    ids = []
    messages = []
    email = IMAP4_SSL(host)
    email.login(username, password)

    # Only mark as read in production to make debugging easier
    email.select(readonly=DEBUG)

    # Get unread e-mail ids sent from MyDenox to parse messages
    # (and mark as unread if it fails to send events to the Server)
    _type, data = email.search(None,
                               'ALL',
                               '(UNSEEN)',
                               '(FROM "{}")'.format(MAIL_FROM))
    ids = data[0].split()

    if len(ids) == 0:
        email.close()
        email.logout()
        raise NoMessages

    debug("Fetching {} new e-mails.".format(len(ids)))
    for num in ids:
        _type, data = email.fetch(num, '(RFC822)')
        messages += [data[0][1].decode('utf-8')]
    email.close()
    email.logout()

    debug("Fetched e-mails.")
    return ids, messages
コード例 #8
0
 def connect(self):
     if self.source_id and self.source_id.id:
         self.ensure_one()
         if self.source_id.type == 'imap':
             if self.source_id.is_ssl:
                 connection = IMAP4_SSL(self.source_id.server,
                                        int(self.source_id.port))
             else:
                 connection = IMAP4(self.source_id.server,
                                    int(self.source_id.port))
             connection.login(self.user, self.password)
         elif self.type == 'pop':
             if self.source_id.is_ssl:
                 connection = POP3_SSL(self.source_id.server,
                                       int(self.source_id.port))
             else:
                 connection = POP3(self.source_id.server,
                                   int(self.source_id.port))
             # TODO: use this to remove only unread messages
             # connection.user("recent:"+server.user)
             connection.user(self.user)
             connection.pass_(self.password)
         # Add timeout on socket
         connection.sock.settimeout(MAIL_TIMEOUT)
         return connection
     return super(vieterp_fetchmail_server, self).connect()
コード例 #9
0
    def connect(cls, conn_dict):
        """
        Connects to a imap server. SSL should be True if connecting via a SSL
       connection

        :return: a ImapClient object with a imaplib.Imap connection and a
        """
        #TODO add in google API here, more secure i think
        host = conn_dict.get('host')
        port = conn_dict.get('port')
        email = conn_dict.get('email')
        password = conn_dict.get('password')
        mailbox = conn_dict.get('mailbox')
        SSL = conn_dict.get('SSL')
        try:
            if SSL is False:
                connection = IMAP4(host=host, port=port)
            else:
                connection = IMAP4_SSL(host=host, port=port)
        except Exception as e:
            raise e
        connection.login(email, password)
        connection.select(mailbox=mailbox)

        return cls(conn_dict, connection)
コード例 #10
0
def initializeInbox():
    global emailID, emailPassword, IMAPServer, IMAPPort

    box = IMAP4_SSL(IMAPServer, IMAPPort)
    box.login(emailID, emailPassword)

    return box
コード例 #11
0
def testEmailConnection(details=None):
    global emailID, emailPassword
    global IMAPServer, IMAPPort

    if details != None:
        TEST_EmailID = details['EmailID']
        TEST_EmailPassword = details['EmailPassword']
        TEST_IMAPServer = details['IMAPServer']
        TEST_IMAPPort = details['IMAPPort']
    else:
        TEST_EmailID = emailID
        TEST_EmailPassword = emailPassword
        TEST_IMAPServer = IMAPServer
        TEST_IMAPPort = IMAPPort

    print('Test email ID:		' + TEST_EmailID)
    print('Test email ID:		' + '*' * len(TEST_EmailPassword))
    print('Test IMAP Server:	' + TEST_IMAPServer)
    print('Test IMAP Port:		' + TEST_IMAPPort)

    try:
        box = IMAP4_SSL(TEST_IMAPServer, TEST_IMAPPort)
        box.login(TEST_EmailID, TEST_EmailPassword)
        reply = box.noop()

        if reply[0] == 'OK':
            print('Passed')
            return True

        else:
            print('Failed Login')
    except:
        print('Failed to connect to Server')

    return False
コード例 #12
0
def process_user(emailAddress):
    logging.info('Processing: %s', emailAddress)
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.verify_mode = ssl.CERT_REQUIRED
    context.check_hostname = True
    context.load_default_certs()

    M = IMAP4_SSL(host=constants.IMAP_HOST,
                  port=constants.IMAP_PORT,
                  ssl_context=context)
    logging.info('IMAP connection made')
    # construct the user login
    userLogin = emailAddress + '*' + constants.IMAP_MASTER_USER

    M.login(userLogin, constants.IMAP_MASTER_PASSWORD)
    logging.info('User logged in')

    M.select(constants.IMAP_SPAM_FOLDER)
    process_folder(M, constants.DSPAM_SPAM_ACTION, emailAddress)

    M.select(constants.IMAP_HAM_FOLDER)
    process_folder(M, constants.DSPAM_HAM_ACTION, emailAddress)
    M.expunge()
    M.close()
    M.logout()
コード例 #13
0
 def start(self, event):
     imap = IMAP4_SSL(config['imap_host'])
     imap.login(config['imap_user'], config['imap_pass'])
     imap.select('INBOX')
     self.imap = imap
     self.get_roster()
     self.send_presence(pnick='imapbot')
コード例 #14
0
ファイル: __init__.py プロジェクト: Mefistous/zato-labs
 def connect(self):
     if self.imap_ssl:
         self.conn = IMAP4_SSL(self.imap_host, int(self.imap_port))
     else:
         self.conn = IMAP4(self.imap_host, int(self.imap_port))
     self.conn.login(self.imap_user, self.imap_pass)
     return self.conn
コード例 #15
0
def Get():
	def get_body(msg):
		if msg.is_multipart():
			return get_body(msg.get_payload(0))
		else:
			return msg.get_payload(None,True)
	prev_MSG = ""



	mail = IMAP4_SSL("imap.gmail.com")
	mail.login(server_name,server_password)
	mail.select('inbox')
	type, data = mail.search(None, 'ALL') 

	id_list = data[0].split()   
	typ, data = mail.fetch(id_list[-1], '(RFC822)' )



	raw = message_from_bytes(data[0][1])
	#Date = raw["Date"].upper()
	cur_MSG = get_body(raw).decode() 

	if prev_MSG != cur_MSG:
		prev_MSG = cur_MSG
		print(cur_MSG)
		#return "RECEIVED ON \r\n" + Date +":\r\n\r\n" + Fernet(enc_key).decrypt(("gAAAAABe" + cur_MSG).encode()).decode()
		return "RECEIVED:\r\n\r\n" + Fernet(enc_key).decrypt(("gAAAAABe" + cur_MSG).encode()).decode()
コード例 #16
0
ファイル: imap.py プロジェクト: 18734865664/python
def recevie_mail():
    try:
        # 实例化imap服务器
        recevie_server = IMAP4_SSL(imap_server)
        recevie_server.login(user, password)
        # recevie_server.list()    # 查看所有的文件夹(IMAP可以支持创建文件夹)
        # recevie_server.select("Inbox")  # 默认选择文件夹是“INBOX”
        # recevie_server.search(None, "ALL")  # 两个参数,第一个是charset,通常为None(ASCII),第二个参数决定检索的关键字,ALL表示所有邮件,SEEN表示已读邮件,NEW表示未读邮件,参考http://afterlogic.com/mailbee-net/docs/MailBee.ImapMail.Imap.Search_overload_2.html
        # recevie_server.fetch(messages_set, message_parts), 两个参数,第一个是邮件的索引,第二个是决定是抓取message中的哪些部分,参考文档http://james.apache.org/server/rfclist/imap4/rfc2060.txt
        recevie_server.select()
        print("+" * 10 + "获取单份邮件" + "+" * 10)
        import pdb
        pdb.set_trace()
        print(
            recevie_server.fetch(
                recevie_server.select("Inbox")[1][0].decode(),
                "(BODY[HEADER])")[1][0][1].decode())
        print("+" * 10 + "获取多份邮件" + "+" * 10)
        for i in recevie_server.fetch("98:100", "(BODY[HEADER])")[1]:
            try:
                print(i[1].decode())
                print("+" * 30 + "\n")
            except:
                pass

    except Exception as err:
        print(err)
    finally:
        recevie_server.logout()
コード例 #17
0
    def imap(self):
        from imaplib import IMAP4_SSL
        if self.__imap is None:
            if not self.username or not self.password:
                raise Exception('Username/password not supplied')

            self.__imap = IMAP4_SSL('imap.gmail.com')
            self.__imap.login(self.username, self.password)
            log('Connected to Gmail IMAP')

        # verify if the specified folder exists
        f = self.__imap.status(self.folder, '(MESSAGES)')
        if (f[0] == 'OK'):
            # everything is fine, the folder exists
            pass
        elif (f[0] == 'NO'):
            # the folder does not exist
            f_p = self.folder.split('/')
            f_here = ''
            for f_c in f_p:
                if (f_here == ''):
                    f_here = f_c
                else:
                    f_here += '/' + f_c
                # check if this folder exists
                f2 = self.__imap.status(f_here, '(MESSAGES)')
                if (f2[0] == 'NO'):
                    self.__imap.create(f_here)
                    log("Create mailbox: " + f_here)
        else:
            raise Exception('Internal error quering the folder status')

        return self.__imap
コード例 #18
0
    def open_mailbox_gmail_oauth(self, **kwargs):
        """Open IMAP email client session to given ``host`` with given ``user`` and ``password``.

        Arguments:
        - ``host``: The IMAP host server. (Default None)
        - ``is_secure``: An indicator flag to connect to IMAP host securely or not. (Default True)
        - ``password``: The plaintext password to be use to authenticate mailbox on given ``host``.
        - ``port``: The IMAP port number. (Default None)
        - ``user``: The username to be use to authenticate mailbox on given ``host``.
        - ``folder``: The email folder to read from. (Default INBOX)

        Examples:
        | Open Mailbox | host=HOST | user=USER | password=SECRET |
        | Open Mailbox | host=HOST | user=USER | password=SECRET | is_secure=False |
        | Open Mailbox | host=HOST | user=USER | password=SECRET | port=8000 |
        | Open Mailbox | host=HOST | user=USER | password=SECRET | folder=Drafts
        """
        self._imap = IMAP4_SSL('imap.gmail.com')
        self._imap.debug = 1  # integer from 0 to 5 where 0 disables debug output and 5 enables full output with wire logging and parsing logs
        folder = '"%s"' % str(kwargs.pop('folder', self.FOLDER))
        user = str(kwargs.pop('user', None))
        access_token = str(kwargs.pop('accessToken', None))
        access_string = 'user=%s\1auth=Bearer %s\1\1' % (user, access_token)
        #access_string = base64.b64encode(access_string.encode()).decode()
        self._imap.authenticate('XOAUTH2', lambda x: access_string)
        self._imap.select(folder)
        self._init_multipart_walk()
コード例 #19
0
def main():
    """Where it all begins."""

    global logger
    logger = tutil.setup_logging("camfetchers errors")
    check_version()

    if 'CF_TIMEOUT' in os.environ:
        timeout = float(os.environ['CF_TIMEOUT'])
        logger.debug("Setting timeout to %.2f" % timeout)
        socket.setdefaulttimeout(timeout)

    with IMAP4_SSL(tutil.get_env_var('IMAPSERVER')) as M:
        try:
            M.login(tutil.get_env_var('CF_USER'),
                    tutil.get_env_var('CF_PASSWD'))
        except IMAP4.error:
            tutil.exit_with_error("Login failed.")

        for cam in tutil.get_env_var('CF_CAMS').split(':'):
            rv, data = M.select(cam)
            if rv == 'OK':
                logger.debug("Processing mailbox %s", cam)
                process_mailbox(M, cam)
            else:
                msg = "Received non-OK response opening mailbox %s, " \
                      + "lets skip this one. (%s)"
                logger.error(msg.format(cam, rv))

    logger.debug("That's all for now, bye.")
    logging.shutdown()
コード例 #20
0
    def connect(self, server='', username='', password='', ssl=True):
        if server != '': self.server = server
        if username != '': self.username = username
        if password != '': self.password = password

        self.conn = IMAP4_SSL(self.server) if self.ssl else IMAP4(self.server)
        self.conn.login(self.username, self.password)
コード例 #21
0
ファイル: imap.py プロジェクト: johnjones4/Doomsday-Machine
def execute_imap(logger, config, job):
    syncer = SyncMap(job)
    if job["options"]["ssl"]:
        imap = IMAP4_SSL(job["options"]["host"], port=job["options"]["port"])
    else:
        imap = IMAP4(job["options"]["host"], port=job["options"]["port"])
    if job["options"]["tls"]:
        imap.starttls()
    imap.login(job["options"]["username"], job["options"]["password"])
    for mailbox in job["options"]["mailboxes"]:
        logger.info(f"Downloading {mailbox}")
        mbox_folder = path.join(job["output_folder"], format_filename(mailbox))
        if not path.isdir(mbox_folder):
            os.mkdir(mbox_folder)
        imap.select(mailbox)
        since_timestamp = syncer.get_last_modified(mailbox)
        if since_timestamp == 0:
            logger.debug("Doing deep search of mailbox")
            downloaded = None
            start = date.today()
            end = start - timedelta(days=30)
            while downloaded != 0:
                logger.debug(f"Searching {str(start)} to {str(end)}")
                criteria = f"(BEFORE {start.strftime('%d-%b-%Y')}) (SINCE {end.strftime('%d-%b-%Y')})"
                downloaded = search_mail(logger, imap, mbox_folder, criteria)
                start = end
                end = start - timedelta(days=30)
        else:
            since = date.fromtimestamp(since_timestamp)
            logger.debug(f"Searching since {str(since)}")
            criteria = "(SINCE " + since.strftime("%d-%b-%Y") + ")"
            search_mail(logger, imap, mbox_folder, criteria)
        syncer.set_last_modified(mailbox, time.time())
        syncer.save()
    syncer.close()
コード例 #22
0
    def get_imap_gm_mail(self, stop_function=lambda: False, timeout=10):
        criteria = u'Важный заголовок'.encode('utf-8')

        while True:
            if stop_function():
                yield None

            try:
                self.imap_gm_server = IMAP4_SSL(self.imap_ssl_gm_host,
                                                self.imap_ssl_gm_port)
                self.imap_gm_server.login(self.imap_gm_username,
                                          self.imap_gm_password)
                self.imap_gm_server.select('INBOX')
                self.imap_gm_server.literal = criteria
                res, data = self.imap_gm_server.uid('SEARCH', 'CHARSET',
                                                    'UTF-8', 'SUBJECT')
                uids = [int(s) for s in data[0].split()]
                for uid in uids:
                    # Fetch entire message
                    res, data = self.imap_gm_server.uid(
                        'FETCH', uid, '(RFC822)')
                    msg = email.message_from_string(data[0][1])
                    text = self.get_first_text_block(msg)
                    self.imap_gm_server.uid('STORE', uid, '+FLAGS',
                                            '(\\Deleted)')
                    self.imap_gm_server.expunge()
                    yield text

                self.imap_gm_server.close()
                self.imap_gm_server.logout()
                self.imap_gm_server = None
                if len(uids) == 0:
                    time.sleep(timeout)
            except Exception as err:
                print(err)
コード例 #23
0
def main():
    with IMAP4_SSL(IMAP_ADDRESS) as imap:
        imap.noop()
        imap.xatom(f'ID ("name" "{APP_NAME}" "version" "{APP_VERSION}")')
        imap.login(USER_NAME, IMAP_TOKEN)
        emails = []
        for folder in imap.list()[1]:
            if folder.startswith(b'() "/" "'):
                byte_folder_name = folder[8:-1]
                print(byte_folder_name)
                folder_name = decode_folder_name(byte_folder_name)
                print(folder_name)
                print(byte_folder_name.decode("ascii"))
                res = imap.select(f'"{byte_folder_name.decode("ascii")}"',
                                  readonly=True)
                print(res)
                if (res[0] != 'OK'):
                    raise Exception()
                print("fetching unread emails")
                mail_ids = imap.search(None, 'UnSeen')[1][0]
                folder_emails = fetch_emails(imap, mail_ids)
                for email in folder_emails:
                    email["folder"] = folder_name
                    email["utf7-folder"] = byte_folder_name.decode("ascii")
                emails += folder_emails
                print("====")
        print("done!")
        print(f"Total unread: {len(emails)}")
        print(emails)
コード例 #24
0
ファイル: snippet.py プロジェクト: someburner/GistsHub
def imap4(host, user, password):
    tests = [IMAP4(host), IMAP4_SSL(host)]
    for test in tests:
        test.debug = 3
        test.login(user, password)
        test.noop()
        test.logout()
コード例 #25
0
def get_imap(mailbox='INBOX'):
    """Instantiate a new IMAP object, login, and connect to a mailbox.
    """
    imap = IMAP4_SSL(settings.EMAIL_HOST)
    imap.login(settings.EMAIL_USER, settings.EMAIL_PASSWORD)
    imap.select(mailbox)
    return imap
コード例 #26
0
ファイル: email_mirror.py プロジェクト: scrapcode/zulip
def get_imap_messages() -> Generator[EmailMessage, None, None]:
    # We're probably running from cron, try to batch-process mail
    if (
        not settings.EMAIL_GATEWAY_BOT
        or not settings.EMAIL_GATEWAY_LOGIN
        or not settings.EMAIL_GATEWAY_PASSWORD
        or not settings.EMAIL_GATEWAY_IMAP_SERVER
        or not settings.EMAIL_GATEWAY_IMAP_PORT
        or not settings.EMAIL_GATEWAY_IMAP_FOLDER
    ):
        raise CommandError(
            "Please configure the email mirror gateway in /etc/zulip/, "
            "or specify $ORIGINAL_RECIPIENT if piping a single mail."
        )
    mbox = IMAP4_SSL(settings.EMAIL_GATEWAY_IMAP_SERVER, settings.EMAIL_GATEWAY_IMAP_PORT)
    mbox.login(settings.EMAIL_GATEWAY_LOGIN, settings.EMAIL_GATEWAY_PASSWORD)
    try:
        mbox.select(settings.EMAIL_GATEWAY_IMAP_FOLDER)
        try:
            status, num_ids_data = mbox.search(None, "ALL")
            for message_id in num_ids_data[0].split():
                status, msg_data = mbox.fetch(message_id, "(RFC822)")
                assert isinstance(msg_data[0], tuple)
                msg_as_bytes = msg_data[0][1]
                message = email.message_from_bytes(msg_as_bytes, policy=email.policy.default)
                # https://github.com/python/typeshed/issues/2417
                assert isinstance(message, EmailMessage)
                yield message
                mbox.store(message_id, "+FLAGS", "\\Deleted")
            mbox.expunge()
        finally:
            mbox.close()
    finally:
        mbox.logout()
コード例 #27
0
def Start_UID_new_email():  # проверка новых писем
    global msgs, M

    while True:
        try:
            inet()  # проверяем наличие интерната с задержкой 5 сек

            try:
                if UID_new_email() != False:  # если есть новое письмо
                    new_email(last_uid)
#                print('ok')  # для тестов

            except Exception:
                print('ERROR POST')  # для тестов
                try:
                    M = IMAP4_SSL('imap.mail.ru')
                    M.login('*****@*****.**', 'Asdf210781')
                    msgs = M.select(
                        'inbox'
                    )  # подключаемся к папке входящие. пример ('OK', [b'8'])

                except Exception:
                    continue


#                continue
        except Exception:
            print('Inet OFF')  # для тестов
            continue
コード例 #28
0
def test_imap_reading(username, password):
    """Test receiving message from the IMAP server."""
    with IMAP4_SSL("localhost", IMAP_PORT) as m:
        m.login(username, password)
        typ, data = m.select()
        assert typ == "OK", "Select did not return OK status"
        message_count = int(data[0])
        print(f"inbox message count: {message_count}")
        typ, data = m.search(None, "ALL")
        assert typ == "OK", "Search did not return OK status"
        message_numbers = data[0].split()
        for num in message_numbers:
            typ, data = m.fetch(num, "(RFC822)")
            assert typ == "OK", f"Fetch of message {num} did not return OK status"
            print("-" * 40)
            print(f"Message: {num}")
            print(data[0][1].decode("utf-8"))
            # mark messag as deleted
            typ, data = m.store(num, "+FLAGS", "\\Deleted")
            assert (
                typ == "OK"
            ), f"Storing '\\deleted' flag on message {num} did not return OK status"
        # expunge all deleted messages
        typ, data = m.expunge()
        assert typ == "OK", "Expunge did not return OK status"
コード例 #29
0
    def __init__(self):
        self._tg = Telegram()
        self._links_to_check = config('Links-to-Check', cast=Csv(strip=' %*'))

        self._service = IMAP4_SSL(config('Email-IMAP'))
        status, _ = self._service.login(config('Email-ID'),
                                        config('Email-Password'))  # login
コード例 #30
0
def get_email_body(key, value):
    """ 
	Uses IMAP to search through your inbox for emails matching your specific criteria.
	After finding your matches it will return all matching emails body fields in a list.
	Possible IMAP search keys can be found here: https://tools.ietf.org/html/rfc3501#section-6.4.4
	"""
    with IMAP4_SSL(imap_url) as session:
        session.login(username, password)
        session.select('INBOX')
        _, messages = session.uid('search', key, value)
        messages = messages[0].split()
        body_container = []

        for message in messages:
            message = session.uid('fetch', message, "(RFC822)")
            msg = email.message_from_bytes(message[1][0][1])

            if msg.is_multipart():
                for part in msg.walk():
                    if part.get_content_type() == "text/plain":
                        body = part.get_payload(decode=True)
                        body = body.decode('latin-1')
            else:
                body = part.get_payload(decode=True)
                body = body.decode('latin-1')

            body_container.append(body)

        return body_container