Python imaplib.IMAP4_SSL Examples

The following are 30 code examples of imaplib.IMAP4_SSL(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module imaplib , or try the search function .
Example #1
Source File: paymentbot.py    From lokun-record with GNU Affero General Public License v3.0 6 votes vote down vote up
def check(user, passwd):
    try:
        i = imaplib.IMAP4_SSL("imap.gmail.com")
        i.login(user, passwd)
    except imaplib.IMAP4.error as ex:
        log(ex)
        sys.exit(1)
    i.select()
    status, response = i.search(None, 'ALL')
    mailids = [int(a) for a in response[0].split()]
    my_mailid = model.DB.get().max_mailid()
    new_mailids = [a+1 for a in range(my_mailid, max(mailids))]

    for mailid in new_mailids:
        log("I'm at: " + str(mailid))
        f = i.fetch(mailid, '(RFC822)')
        mail = f[1][0][1]
        info = f[1][0][0]
        process(mail)
        model.DB.get().add_mailid(mailid)

    i.close()
    i.logout() 
Example #2
Source File: basebot.py    From lockebot with MIT License 6 votes vote down vote up
def open_connection():
    """Opens the connection to the email service by use of the stored
    credentials"""

    # TODO: find a more sensible and secure approach or at least recommend
    # securing the credential file and add handling in the event of being
    # unable to read it.

    # Read the config file
    config = ConfigParser.ConfigParser()
    config.read([os.path.abspath(os.path.join('config', 'settings.ini'))])

    # Connect to the server
    hostname = config.get('server', 'imap-hostname')
    logger.debug('Connecting to ' + hostname)
    connection = imaplib.IMAP4_SSL(hostname, 993)

    # Login to our account
    username = config.get('account', 'username')
    password = config.get('account', 'password')
    logger.debug('Logging in as ' + username)
    connection.login(username, password)
    return connection 
Example #3
Source File: email_lean.py    From notes with Apache License 2.0 6 votes vote down vote up
def receive_imap_email():
    imap = imaplib.IMAP4_SSL(imap_server)
    imap.login(user, password)
    response, data = imap.list()
    print(response)
    print(data[0])
    print(data[1:3])
    response, data = imap.select('INBOX')
    print(response)
    print(data)
    imap.select(settings.EMAIL_GATEWAY_IMAP_FOLDER)
    status, num_ids_data = imap.search(None, 'ALL')
    for id in ids:
        res, featch_data = imap.fetch(str.encode(str(id)), '(RFC822)')
        print(res)
        if featch_data[0] is not None:
            for part in email.message_from_string(str(featch_data[0][1])).walk():
                print(part.get_payload(decode=True)) 
Example #4
Source File: __init__.py    From imap-cli with MIT License 6 votes vote down vote up
def disconnect(imap_account):
    """Disconnect IMAP account object

    .. versionadded:: 0.1

    Example:

    >>> import imap_cli
    >>> from imap_cli import config
    >>> conf = config.new_context_from_file(section='imap')
    >>> imap_account = imap_cli.connect(**conf)
    >>> imap_account
    <imaplib.IMAP4_SSL instance at 0x7fccd57579e0>
    >>> imap_cli.change_dir(imap_account, 'INBOX')
    >>> imap_cli.disconnect(imap_account)
    """
    log.debug('Disconnecting from {}'.format(imap_account.host))
    if imap_account.state == 'SELECTED':
        imap_account.close()
    if imap_account.state != 'LOGOUT':
        imap_account.logout() 
Example #5
Source File: checker.py    From root-2015-tasks with GNU General Public License v3.0 6 votes vote down vote up
def get_imap(server, sender, user):
    result = FAIL
    try:
        box = imaplib.IMAP4_SSL(server)
        box.login(*user)
        box.select()
        typ, data = box.search(None, 'FROM', '"{0}"'.format(sender[0]))
        for num in data[0].split():
            typ, data = box.fetch(num, '(RFC822)')
            if content.format(sender[0]) in data[0][1]:
                result = OK
            box.store(num, '+FLAGS', '\\Deleted')

        box.expunge()
        box.close()
        box.logout()
        return result
    except Exception as e:
        print "IMAP error: {0}".format(e)
        return FAIL 
Example #6
Source File: Testimap.py    From fuzzdb-collect with GNU General Public License v3.0 6 votes vote down vote up
def check(email, password):
    try:
        email = email
        password = password
        imap_server = "imap.163.com"
        server = imaplib.IMAP4_SSL(imap_server)
        server.login(email, password)
        #print('Messages: %s. Size: %s' % server.s())
        print(email+": successful")
    except Exception as e:
        print(email+":fail")
        print(e) 
Example #7
Source File: test_imapcli.py    From imap-cli with MIT License 5 votes vote down vote up
def test_wrong_change_dir(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        assert imap_cli.change_dir(self.imap_account, 'NotADirectory') == -1 
Example #8
Source File: imaprelayclient.py    From CVE-2019-1040 with MIT License 5 votes vote down vote up
def initConnection(self):
        self.session = imaplib.IMAP4_SSL(self.targetHost,self.targetPort)
        self.authTag = self.session._new_tag()
        LOG.debug('IMAP CAPABILITIES: %s' % str(self.session.capabilities))
        if 'AUTH=NTLM' not in self.session.capabilities:
            LOG.error('IMAP server does not support NTLM authentication!')
            return False
        return True 
Example #9
Source File: mailagent.py    From huobi-autotrading with MIT License 5 votes vote down vote up
def __init__(self, account, auth_code, name='', **config):
        account_name, server_name = account.split('@')

        self.smtp = 'smtp.' + server_name
        self.imap = 'imap.' + server_name
        self.smtp_port = 0
        self.imap_port = 0
        self.use_ssl = True

        self.__dict__.update(SERVER_LIB.get(server_name, {}))
        self.__dict__.update(config)

        self.name = '%s <%s>' % (name or account_name, account)
        self.account = account
        self.auth_code = auth_code

        st_SMTP = smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP
        st_IMAP = imaplib.IMAP4_SSL if self.use_ssl else imaplib.IMAP4

        if self.smtp_port:
            self.st_SMTP = lambda: st_SMTP(self.smtp, self.smtp_port)
        else:
            self.st_SMTP = lambda: st_SMTP(self.smtp)

        if self.imap_port:
            self.st_IMAP = lambda: st_IMAP(self.imap, self.imap_port)
        else:
            self.st_IMAP = lambda: st_IMAP(self.imap)

        self.SMTP = lambda: SMTP(self)
        self.IMAP = lambda: IMAP(self) 
Example #10
Source File: receiver.py    From helfertool with GNU Affero General Public License v3.0 5 votes vote down vote up
def connect(self):
        """
        Connect to IMAP server and select given folder.
        """
        if self._connection:
            raise MailHandlerError("IMAP connection already opened")

        # connect
        try:
            if settings.RECEIVE_EMAIL_USE_SSL:
                self._connection = imaplib.IMAP4_SSL(host=settings.RECEIVE_EMAIL_HOST,
                                                     port=settings.RECEIVE_EMAIL_PORT)
            else:
                self._connection = imaplib.IMAP4(host=settings.RECEIVE_EMAIL_HOST,
                                                 port=settings.RECEIVE_EMAIL_PORT)

            if settings.RECEIVE_EMAIL_USE_TLS:
                self._connection.starttls()
        except imaplib.IMAP4.error:
            raise MailHandlerError("Invalid hostname, port or TLS settings for IMAP")

        # login
        try:
            self._connection.login(settings.RECEIVE_EMAIL_HOST_USER, settings.RECEIVE_EMAIL_HOST_PASSWORD)
        except imaplib.IMAP4.error:
            raise MailHandlerError("Invalid username or password for IMAP")

        # select folder
        try:
            ret, data = self._connection.select(settings.RECEIVE_EMAIL_FOLDER)

            if ret != "OK":
                raise MailHandlerError("Invalid folder")
        except imaplib.IMAP4.error:
            raise MailHandlerError("Invalid folder") 
Example #11
Source File: 15_5_check_remote_email_via_imap.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def check_email(username): 
    mailbox = imaplib.IMAP4_SSL(GOOGLE_IMAP_SERVER, '993') 
    password = getpass.getpass(prompt="Enter your Google password: ") 
    mailbox.login(username, password)
    mailbox.select('Inbox')
    typ, data = mailbox.search(None, 'ALL')
    for num in data[0].split():
        typ, data = mailbox.fetch(num, '(RFC822)')
        print ('Message %s\n%s\n' % (num, data[0][1]))
        break
    mailbox.close()
    mailbox.logout() 
Example #12
Source File: _imap.py    From admin4 with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port, security):
    self.sslobj=None
    self.tls=False
    self.lastError=None
    if security == 'SSL':
      self.callClass=imaplib.IMAP4_SSL
    else:
      self.callClass=imaplib.IMAP4
      
    imaplib.IMAP4_SSL.__init__(self, host, port) 
Example #13
Source File: test_status.py    From imap-cli with MIT License 5 votes vote down vote up
def test_status_with_error_imap_response(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.error = True

        statuses = list(imap_cli.status(self.imap_account))
        for directory_status in statuses:
            assert directory_status == {'directory': u'Δiπectòrÿ_ñämé',
                                        'unseen': "0", 'count': "1",
                                        'recent': "1"}
        assert len(statuses) == 0 
Example #14
Source File: test_imapcli.py    From imap-cli with MIT License 5 votes vote down vote up
def setUp(self):
        imaplib.IMAP4 = tests.ImapConnectionMock()
        imaplib.IMAP4_SSL = tests.ImapConnectionMock() 
Example #15
Source File: test_imapcli.py    From imap-cli with MIT License 5 votes vote down vote up
def test_change_dir(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        imap_cli.change_dir(self.imap_account, 'Test') 
Example #16
Source File: test_imapcli.py    From imap-cli with MIT License 5 votes vote down vote up
def test_change_dir_twice(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        assert imap_cli.change_dir(self.imap_account, 'Test') == '1'
        assert imap_cli.change_dir(self.imap_account, 'INBOX') == '1' 
Example #17
Source File: test_search.py    From imap-cli with MIT License 5 votes vote down vote up
def setUp(self):
        imaplib.IMAP4_SSL = tests.ImapConnectionMock() 
Example #18
Source File: test_search.py    From imap-cli with MIT License 5 votes vote down vote up
def test_combine_search_criterion(self):
        self.imap_account = imaplib.IMAP4_SSL()

        date = datetime.datetime(1989, 1, 3)
        mail_address = 'user@example.tld'
        search_criterion = [
            search.create_search_criterion_by_date(date, relative='BEFORE'),
            search.create_search_criterion_by_mail_address(mail_address,
                                                           header_name='TO'),
        ]

        imap_request = search.combine_search_criterion(search_criterion)
        assert imap_request == '(BEFORE 03-Jan-1989 TO "user@example.tld")'

        imap_request = search.combine_search_criterion(search_criterion,
                                                       operator='AND')
        assert imap_request == '(BEFORE 03-Jan-1989 TO "user@example.tld")'

        imap_request = search.combine_search_criterion(search_criterion,
                                                       operator='OR')
        assert imap_request == 'OR BEFORE 03-Jan-1989 TO "user@example.tld"'

        imap_request = search.combine_search_criterion(search_criterion,
                                                       operator='NOT')
        assert imap_request == 'NOT BEFORE 03-Jan-1989 TO "user@example.tld"'

        imap_request = search.combine_search_criterion(search_criterion,
                                                       operator='WRONG')
        assert imap_request == '(BEFORE 03-Jan-1989 TO "user@example.tld")' 
Example #19
Source File: test_imapserver_imaplib.py    From aioimaplib with GNU General Public License v3.0 5 votes vote down vote up
def test_client_can_connect_to_server_over_ssl(self):
        ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=self._cert_file)

        pending_imap = self.loop.run_in_executor(None, functools.partial(
            imaplib.IMAP4_SSL,
            host='127.0.0.1',
            port=12345,
            ssl_context=ssl_context)
        )
        imap_client = yield from asyncio.wait_for(pending_imap, 1)

        self.assertEqual('NONAUTH', imap_client.state) 
Example #20
Source File: __init__.py    From imap-cli with MIT License 5 votes vote down vote up
def connect(hostname, username, password=None, port=None, ssl=True,
            sasl_auth=None, sasl_ir=None):
    """Return an IMAP account object (see imaplib documentation for details)

    .. versionadded:: 0.1

    Example:

    >>> import imap_cli
    >>> from imap_cli import config
    >>> conf = config.new_context_from_file(section='imap')
    >>> imap_cli.connect(**conf)
    <imaplib.IMAP4_SSL instance at 0x7fccd57579e0>
    """
    if port is None:
        port = const.DEFAULT_PORT if ssl is False else const.DEFAULT_SSL_PORT

    if ssl is True:
        log.debug('Connecting with SSL on {}'.format(hostname))
        imap_account = imaplib.IMAP4_SSL(hostname, port)
    else:
        log.debug('Connecting on {}'.format(hostname))
        imap_account = imaplib.IMAP4(hostname, port)

    if sasl_auth:
        imap_account.authenticate(sasl_auth, lambda x: sasl_ir)
    else:
        imap_account.login(username, password)
    return imap_account 
Example #21
Source File: imap.py    From eavatar-me with Apache License 2.0 5 votes vote down vote up
def check_gmail(username, password):
    """Check GMail

    E.g.
        messages,unseen = imap.check_gmail('username@gmail.com','password')
    :param username:
    :param password:
    :return:
    """
    i = imaplib.IMAP4_SSL('imap.gmail.com')
    try:
        i.login(username, password)
        x, y = i.status('INBOX', '(MESSAGES UNSEEN)')
        messages = int(re.search('MESSAGES\s+(\d+)', y[0]).group(1))
        unseen = int(re.search('UNSEEN\s+(\d+)', y[0]).group(1))
        return messages, unseen
    except:
        return False, 0 
Example #22
Source File: 5_5_check_remote_email_via_imap.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def check_email(username): 
    mailbox = imaplib.IMAP4_SSL(GOOGLE_IMAP_SERVER, '993') 
    password = getpass.getpass(prompt="Enter your Google password: ") 
    mailbox.login(username, password)
    mailbox.select('Inbox')
    typ, data = mailbox.search(None, 'ALL')
    for num in data[0].split():
        typ, data = mailbox.fetch(num, '(RFC822)')
        print ('Message %s\n%s\n' % (num, data[0][1]))
        break
    mailbox.close()
    mailbox.logout() 
Example #23
Source File: mailboxresource.py    From imapbox with MIT License 5 votes vote down vote up
def get_folder_fist(account):
    mailbox = imaplib.IMAP4_SSL(account['host'], account['port'])
    mailbox.login(account['username'], account['password'])
    folder_list = mailbox.list()[1]
    mailbox.logout()
    return folder_list 
Example #24
Source File: mailboxresource.py    From imapbox with MIT License 5 votes vote down vote up
def __init__(self, host, port, username, password, remote_folder):
        self.mailbox = imaplib.IMAP4_SSL(host, port)
        self.mailbox.login(username, password)
        typ, data = self.mailbox.select(remote_folder, readonly=True)
        if typ != 'OK':
            # Handle case where Exchange/Outlook uses '.' path separator when
            # reporting subfolders. Adjust to use '/' on remote.
            adjust_remote_folder = re.sub('\.', '/', remote_folder)
            typ, data = self.mailbox.select(adjust_remote_folder, readonly=True)
            if typ != 'OK':
                print("MailboxClient: Could not select remote folder '%s'" % remote_folder) 
Example #25
Source File: run_autoresponder.py    From python-email-autoresponder with MIT License 5 votes vote down vote up
def do_connect_to_imap():
    global incoming_mail_server
    incoming_mail_server = imaplib.IMAP4_SSL(config['in.host'], config['in.port'])
    (retcode, capabilities) = incoming_mail_server.login(config['in.user'], config['in.pw'])
    if retcode != "OK":
        shutdown_with_error("IMAP login failed! Return code: '" + cast(retcode, str) + "'.") 
Example #26
Source File: run_autoresponder.py    From python-email-autoresponder with MIT License 5 votes vote down vote up
def connect_to_imap():
    try:
        do_connect_to_imap()
    except gaierror:
        shutdown_with_error("IMAP connection failed! Specified host not found.")
    except imaplib.IMAP4_SSL.error as e:
        shutdown_with_error("IMAP login failed! Reason: '" + cast(e.args[0], str, 'UTF-8') + "'.")
    except Exception as e:
        shutdown_with_error("IMAP connection/login failed! Reason: '" + cast(e, str) + "'.") 
Example #27
Source File: siricontrol.py    From SiriControl-System with MIT License 5 votes vote down vote up
def __init__(self, username, password):
        print("------------------------------------------------------")
        print("-                    SIRI CONTROL                    -")
        print("-           Created by Sanjeet Chatterjee            -")
        print("-      Website: https://medium.com/@thesanjeetc      -")
        print("------------------------------------------------------")

        try:
            self.last_checked = -1
            self.mail = imaplib.IMAP4_SSL("imap.gmail.com", 993)
            self.mail.login(username, password)
            self.mail.list()
            self.mail.select("Notes")

            # Gets last Note id to stop last command from executing
            result, uidlist = self.mail.search(None, "ALL")
            try:
                self.last_checked = uidlist[0].split()[-1]
            except IndexError:
                pass

            self.load()
            self.handle()
        except imaplib.IMAP4.error:
            print("Your username and password is incorrect")
            print("Or IMAP is not enabled.") 
Example #28
Source File: imap.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def authenticate(self, url, consumer, token):
        if consumer is not None and not isinstance(consumer, oauth2.Consumer):
            raise ValueError("Invalid consumer.")

        if token is not None and not isinstance(token, oauth2.Token):
            raise ValueError("Invalid token.")

        imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH',
            lambda x: oauth2.build_xoauth_string(url, consumer, token)) 
Example #29
Source File: Demo_Desktop_Widget_Email_Notification.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def read_mail(window):
    """
    Reads late emails from IMAP server and displays them in the Window
    :param window: window to display emails in
    :return:
    """
    mail = imaplib.IMAP4_SSL(IMAP_SERVER)

    (retcode, capabilities) = mail.login(LOGIN_EMAIL, LOGIN_PASSWORD)
    mail.list()
    typ, data = mail.select('Inbox')
    n = 0
    now = datetime.now()
    # get messages from today
    search_string = '(SENTON {}-{}-{})'.format(now.day,
                                               calendar.month_abbr[now.month], now.year)
    (retcode, messages) = mail.search(None, search_string)
    if retcode == 'OK':
        # message numbers are separated by spaces, turn into list
        msg_list = messages[0].split()
        msg_list.sort(reverse=True)  # sort messages descending
        for n, message in enumerate(msg_list):
            if n >= MAX_EMAILS:
                break

            from_elem = window['{}from'.format(n)]
            date_elem = window['{}date'.format(n)]
            from_elem.update('')  # erase them so you know they're changing
            date_elem.update('')
            window.refresh()

            typ, data = mail.fetch(message, '(RFC822)')
            for response_part in data:
                if isinstance(response_part, tuple):

                    original = email.message_from_bytes(response_part[1])
                    date_str = original['Date'][:22]

                    from_elem.update(original['From'])
                    date_elem.update(date_str)
                    window.refresh()  # make the window changes show up right away 
Example #30
Source File: Demo_Desktop_Widget_Email_Notification.py    From PySimpleGUI with GNU Lesser General Public License v3.0 5 votes vote down vote up
def read_mail(window):
    """
    Reads late emails from IMAP server and displays them in the Window
    :param window: window to display emails in
    :return:
    """
    mail = imaplib.IMAP4_SSL(IMAP_SERVER)

    (retcode, capabilities) = mail.login(LOGIN_EMAIL, LOGIN_PASSWORD)
    mail.list()
    typ, data = mail.select('Inbox')
    n = 0
    now = datetime.now()
    # get messages from today
    search_string = '(SENTON {}-{}-{})'.format(now.day, calendar.month_abbr[now.month], now.year)
    (retcode, messages) = mail.search(None, search_string)
    if retcode == 'OK':
        msg_list = messages[0].split()  # message numbers are separated by spaces, turn into list
        msg_list.sort(reverse=True)  # sort messages descending
        for n, message in enumerate(msg_list):
            if n >= MAX_EMAILS:
                break
            from_elem = window.FindElement('{}from'.format(n))
            date_elem = window.FindElement('{}date'.format(n))
            from_elem.Update('')  # erase them so you know they're changing
            date_elem.Update('')
            window.Refresh()
            typ, data = mail.fetch(message, '(RFC822)')
            for response_part in data:
                if isinstance(response_part, tuple):
                    original = email.message_from_bytes(response_part[1])
                    date_str = original['Date'][:22]
                    from_elem.Update(original['From'])
                    date_elem.Update(date_str)
                    window.Refresh()  # make the window changes show up right away