Ejemplo n.º 1
0
def test_wrong_login_credentials():
    with pytest.raises(e.ConnectionRefused):
        imapy.connect(
            host='nonexistent',
            username='******',
            password='******',
            ssl=True)
    with pytest.raises(imaplib.IMAP4_SSL.error):
        imapy.connect(
            host=host,
            username='******',
            password='******',
            ssl=True)
Ejemplo n.º 2
0
def test_logout():
    with imapy.connect(
            host=host, username=username, password=password, ssl=ssl) as box:
        assert(box.logged_in is True)
    assert(box.logged_in is False)

    box = imapy.connect(
        host=host,
        username=username,
        password=password,
        ssl=ssl)
    assert(box.logged_in is True)
    box.logout()
    assert(box.logged_in is False)
Ejemplo n.º 3
0
def setup_function(module):
    """ Delete all testing folders and empties Trash"""
    box = imapy.connect(
        host=host,
        username=username,
        password=password,
        ssl=ssl)

    folders = box.folders()
    sep = box.separator
    bad_folders = ['imapy-del1', 'imapy-del2', 'imapy-search test',
                   'Imapy-delete', 'Imapy-delete123', 'Imapy тест 123',
                   'Imapy тест 123' + sep + 'Subfolder 456 тест']
    trash_folders = ['Deleted', 'Удаленные', 'Trash',
                     '[Gmail]' + sep + 'Trash']

    for f in folders:
        # delete folders inside trash folder: '[Gmail]/Trash/123'
        for tf in trash_folders:
            if tf in f and tf != f:
                box.folder().delete(f)
        # delete bad folders
        if f in bad_folders:
            box.folder().delete(f)

    # delete messages inside trash folder
    trash_folders = [t.rstrip(sep) for t in trash_folders]
    server_trash_folders = list(set(trash_folders) & set(box.folders()))
    for f in server_trash_folders:
        emails = box.folder(f).emails(-100)
        if emails:
            for em in emails:
                em.delete()
Ejemplo n.º 4
0
def get_some_mail():
    imapObj = imapy.connect(
        host = 'imap.gmail.com',
        username = input('Username: '******'Inbox').emails(-5)
Ejemplo n.º 5
0
def fetch_email(obj):
    
    log = logging.getLogger('fetch')
    log.info('当前时间,%s' % time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))
    log.info('邮件%s抓取邮件,时间为%s' % (obj.address,time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))))
    
    #['INBOX' 'REDSUN测试邮件','已发送',]
    box = imapy.connect(host=obj.imap,username=obj.address,password=obj.password,ssl=False)
    q = Q()
    emails = box.folder('INBOX').emails(q.unseen())
    save_email(emails,'')
    box.logout()
    log.info('邮箱%s抓取完毕 ,时间为%s' % (obj.address,time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))))
Ejemplo n.º 6
0
 def fetch_email_by_folder(self,send):
     #['INBOX' 'REDSUN测试邮件','已发送',]
     box = imapy.connect(host=self.imap,username=self.user,password=self.password,ssl=False)
     #q = Q()
     for item in ['已发送']: 
         print('文件夹为%s抓取邮件,时间为%s' % (item,time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))))
         status = box.folder(item).info()
         total = status['total']
         for i in range(total+10):
             if (i+1)<1995:
                 continue
             print('抓取第:%s封邮件' % (i+1))
             emails = box.folder(item).emails(i+1,i+1)
             if isinstance(emails,bool) :continue
             self.save_email(emails,send,item)
     box.logout()
Ejemplo n.º 7
0
def fetch_email(obj):
    log = logging.getLogger('fetch')
    log.info('当前时间,%s' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
    log.info('邮件%s抓取邮件,时间为%s' % (obj.address, time.strftime("%Y-%m-%d %H:%M:%S",  time.localtime(time.time()))))
    try:
        box = imapy.connect(host=obj.imap, username=obj.address, password=obj.password, ssl=False)
    except Exception as e:
        log.info('发生异常重新执行任务---------%s---------------%s' % (obj.address, e))
        if '%s' % e == '[Errno -2] Name or service not known':
            fetch_email(obj)
        return
    q = Q()
    emails = box.folder('INBOX').emails(q.unseen())
    save_email(emails, '')
    box.logout()
    log.info('邮箱%s抓取完毕 ,时间为%s' % (obj.address, time.strftime("%Y-%m-%d %H:%M:%S",
                                                                 time.localtime(time.time()))))
Ejemplo n.º 8
0
def main():
    log_name = "logfile.log"
    logger = open(log_name, "w")    
    args = sys.argv
    if len(args) != 2:
        print("Invalid number of arguments", file=logger)
        return
    
    conf = args[1]
    if (not os.path.isfile(conf)):
        print("Argument is not a valid file path", file=logger)
        return
    
    try:
        conf = read_configuration(conf)
    except:
        print("Invalid configuration file", file=logger)
        return

    con, box = None, None
    try:
        con = fdb.connect(dsn=conf["db_location"], user=conf["db_lgn"], password=conf["db_pwd"]) 
    except Exception as e:
        print(str(e), file=logger)
        print("Can't establish database connection", file=logger)
        return

    try:
        box = imapy.connect(host=conf["imap_location"], username=conf["imap_lgn"], password=conf["imap_pwd"], ssl=True)
    except Exception as e:
        print(str(e), file=logger)
        print("Can't establish connection to imap server", file=logger)
        return    
    
    try:
        parse_emails(con, box, conf, logger)
        box.logout()
        con.close()
    except Exception as e:
        print(str(e), file=logger)
        print("Something unknown and invalid happened. Sorry.", file=logger)
    logger.close()
Ejemplo n.º 9
0
def fetch_email(obj):

    log = logging.getLogger('fetch')
    log.info('当前时间,%s' %
             time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
    log.info('邮件%s抓取邮件,时间为%s' %
             (obj.address,
              time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))

    #['INBOX' 'REDSUN测试邮件','已发送',]
    box = imapy.connect(host=obj.imap,
                        username=obj.address,
                        password=obj.password,
                        ssl=False)
    q = Q()
    emails = box.folder('INBOX').emails(q.unseen())
    save_email(emails, '')
    box.logout()
    log.info('邮箱%s抓取完毕 ,时间为%s' %
             (obj.address,
              time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
Ejemplo n.º 10
0
def _load_folders(account: Account):
    connection = imapy.connect(host=account.imap_host,
                               port=account.imap_port,
                               username=account.address,
                               password=account.password,
                               ssl=account.imap_ssl)

    folders = connection.folders()

    for folder in account.folders:
        if folder.name not in folders:
            folder.delete_instance(recursive=True)

    top_level_folders = [
        folder for folder in folders if connection.separator not in folder
    ]

    def load_children(parent_folder, parent_name):
        for child in connection.folder(parent_name).children():
            child_folder, _ = Folder.get_or_create(name=child,
                                                   account=account,
                                                   parent=parent_folder)

            if not connection.folder(child).info()['uidnext']:
                child_folder.with_emails = False
                child_folder.save()

            load_children(child_folder, child)

    for folder in top_level_folders:
        new_folder, _ = Folder.get_or_create(name=folder, account=account)

        if not connection.folder(folder).info()['uidnext']:
            new_folder.with_emails = False
            new_folder.save()

        load_children(new_folder, folder)

    connection.logout()
Ejemplo n.º 11
0
def test_search_params():
    box = imapy.connect(host=host,
                        username=username,
                        password=password,
                        ssl=ssl)

    from1 = '*****@*****.**'
    to1 = '*****@*****.**'
    subject1 = 'Samplissimo subject. Всякое разное'
    contents1 = 'Lorem ipsum dorem sit amet.' +\
        'Съешь ещё этих мягких французских булок, да выпей же чаю. ' +\
        'http://www.cnn.com https://wikipedia.org http://del.icio.us'
    bcc1 = '*****@*****.**'
    ecc1 = '*****@*****.**'

    text_email1 = get_text_email(from1, to1, subject1, contents1, bcc1, ecc1)

    # append email to folder
    folder_name = 'imapy-search test'
    box.folder().make_folder(folder_name)
    box.folder(folder_name).append(
        text_email1, flags=['answered', 'draft', 'flagged', 'seen'])

    q = Q()
    with pytest.raises(e.SearchSyntaxNotSupported):
        emails = box.folder(folder_name).emails(
            q.subject('Съешь').sender('ещё'))

    q = Q()
    with pytest.raises(e.WrongDateFormat):
        emails = box.folder(folder_name).emails(q.since('2014-Jan-1'))

    q = Q()
    today = time.strftime('%d-%b-%Y')
    query = q.sender(from1).bcc(bcc1).answered().before('1-Jan-2050').\
        body('ipsum').cc(ecc1).draft().flagged().larger(1).seen().\
        sent_before('1-Jan-2050').sent_since('1-Jan-2014').\
        since('1-Jan-2014').smaller(10000000).text('ipsum').\
        recipient(to1).undeleted().sent_on(today).on(today)

    emails = box.folder(folder_name).emails(query)
    ''' we don't test the amount of results because
        different imap servers handle search differently
        and may not return any results
    '''
    assert isinstance(emails, list)

    q = Q()
    # the queries below are pointless and used only for testing
    query = q.sender('abc').unseen().unflagged().undraft().unanswered().\
        uid('123')
    emails = box.folder(folder_name).emails(query)
    assert isinstance(emails, list)

    q = Q()
    query = q.recent()
    emails = box.folder(folder_name).emails(query)
    assert isinstance(emails, list)

    q = Q()
    query = q.sender('abcsdfsd').old()
    emails = box.folder(folder_name).emails(query)
    assert isinstance(emails, list)

    q = Q()
    query = q.sender('abcsdfsd').new()
    emails = box.folder(folder_name).emails(query)
    assert isinstance(emails, list)

    q = Q()
    query = q.sender('abcsdfsd').\
        header('some-header', 'some value').deleted()
    emails = box.folder(folder_name).emails(query)
    assert isinstance(emails, list)

    box.logout()
Ejemplo n.º 12
0
def test_search_params():
    box = imapy.connect(
        host=host,
        username=username,
        password=password,
        ssl=ssl)

    from1 = '*****@*****.**'
    to1 = '*****@*****.**'
    subject1 = 'Samplissimo subject. Всякое разное'
    contents1 = 'Lorem ipsum dorem sit amet.' +\
        'Съешь ещё этих мягких французских булок, да выпей же чаю. ' +\
        'http://www.cnn.com https://wikipedia.org http://del.icio.us'
    bcc1 = '*****@*****.**'
    ecc1 = '*****@*****.**'

    text_email1 = get_text_email(from1, to1, subject1, contents1, bcc1, ecc1)

    # append email to folder
    folder_name = 'imapy-search test'
    box.folder().make_folder(folder_name)
    box.folder(folder_name).append(
        text_email1,
        flags=['answered', 'draft', 'flagged', 'seen'])

    q = Q()
    with pytest.raises(e.SearchSyntaxNotSupported):
        emails = box.folder(folder_name).emails(
            q.subject('Съешь').sender('ещё')
        )

    q = Q()
    with pytest.raises(e.WrongDateFormat):
        emails = box.folder(folder_name).emails(
            q.since('2014-Jan-1')
        )

    q = Q()
    today = time.strftime('%d-%b-%Y')
    query = q.sender(from1).bcc(bcc1).answered().before('1-Jan-2050').\
        body('ipsum').cc(ecc1).draft().flagged().larger(1).seen().\
        sent_before('1-Jan-2050').sent_since('1-Jan-2014').\
        since('1-Jan-2014').smaller(10000000).text('ipsum').\
        recipient(to1).undeleted().sent_on(today).on(today)

    emails = box.folder(folder_name).emails(
        query
    )
    ''' we don't test the amount of results because
        different imap servers handle search differently
        and may not return any results
    '''
    assert isinstance(emails, list)

    q = Q()
    # the queries below are pointless and used only for testing
    query = q.sender('abc').unseen().unflagged().undraft().unanswered().\
        uid('123')
    emails = box.folder(folder_name).emails(
        query
    )
    assert isinstance(emails, list)

    q = Q()
    query = q.recent()
    emails = box.folder(folder_name).emails(
        query
    )
    assert isinstance(emails, list)

    q = Q()
    query = q.sender('abcsdfsd').old()
    emails = box.folder(folder_name).emails(
        query
    )
    assert isinstance(emails, list)

    q = Q()
    query = q.sender('abcsdfsd').new()
    emails = box.folder(folder_name).emails(
        query
    )
    assert isinstance(emails, list)

    q = Q()
    query = q.sender('abcsdfsd').\
        header('some-header', 'some value').deleted()
    emails = box.folder(folder_name).emails(
        query
    )
    assert isinstance(emails, list)

    box.logout()
Ejemplo n.º 13
0
def test_operations():

    box = imapy.connect(
        host=host,
        username=username,
        password=password,
        ssl=ssl)

    assert isinstance(box, imap.IMAP)
    assert box.lib in (
        imaplib.IMAP4_SSL,
        imaplib.IMAP4,
        imaplib.IMAP4_stream)

    # folders()
    folders = box.folders()
    assert len(folders) > 0
    for f in folders:
        assert len(f) > 0
    folders2 = box.folders()
    assert folders2 == folders

    # no children
    assert box.children() == []

    # folder()
    assert box.selected_folder is None
    box.folder(folders[0])
    assert box.selected_folder is not None

    # children()
    assert type(box.children()) is list
    with pytest.raises(e.NonexistentFolderError):
        box.folder('NonexistentFolder')

    '''

    Create, rename, delete folder

    '''
    # create list of folders
    folders_list = ['imapy-del1', 'imapy-del2']
    box.folder().make_folder(folders_list)
    for f in folders_list:
        assert f in box.folders()

    box.folder().delete(folders_list)
    for f in folders_list:
        assert f not in box.folders()

    # create folder
    delete_name = 'Imapy-delete'
    box.folder().make_folder(delete_name)
    assert delete_name in box.folders()
    with pytest.raises(e.InvalidFolderName):
        box.make_folder('BadFolder' + box.separator + 'Name')

    # rename
    new_name = delete_name + '123'
    box.folder(delete_name).rename(new_name)
    assert new_name in box.folders()
    # delete
    box.folder().delete(new_name)
    assert (new_name) not in box.folders()

    '''

    Create subfolders, append messages, check messages,
    folder info, email search, mark messages with tags,
    delete messages, select parent folder

    '''
    # create folder (ascii + unicode)
    test_folder = 'Imapy тест 123'
    box.folder().make_folder(test_folder)
    assert test_folder in box.mail_folders

    # create subfolder (ascii + unicode)
    test_subfolder = 'Subfolder 456 тест'
    box.folder(test_folder).make_folder(test_subfolder)
    test_folder_full_name = test_folder + box.separator + test_subfolder
    assert test_folder_full_name in box.mail_folders

    from1 = '*****@*****.**'
    to1 = '*****@*****.**'
    subject1 = 'Email subject заголовок -*-'
    test_subject1 = 'subject'
    contents1 = 'Email contents содержание'

    text_email1 = get_text_email(from1, to1, subject1, contents1)

    # check status1 before append
    status1 = box.folder(test_folder).info()
    assert status1['total'] == 0

    # append email to folder
    non_standard_flags = ['really-non-standard-flag', 'weird-flag']
    box.folder(test_folder).append(
        text_email1, flags=non_standard_flags)

    with pytest.raises(e.UnknownEmailMessageType):
        box.folder(test_folder).append({'dummy': 'dict'})

    # check status1 after append
    status1 = box.folder(test_folder).info()
    assert status1['total'] == 1

    # check appended email flags
    emails = box.folder(test_folder).emails(-1)
    for f in non_standard_flags:
        assert f not in emails[0]['flags']

    from2 = '*****@*****.**'
    to2 = '*****@*****.**'
    subject2 = 'Email subject 2заголовок2 -*-'
    test_subject2 = 'subject'
    contents2 = 'Email contents содержание2'

    text_email2 = get_text_email(from2, to2, subject2, contents2)

    children = box.folder(test_folder).children()
    subfolder_name = children[0]

    # check parent selection
    parent_folder_obj = box.folder(test_folder).__dict__
    selected_parent_folder_obj = box.folder(subfolder_name).parent().__dict__
    assert parent_folder_obj == selected_parent_folder_obj

    # check parent selection when parent is already on topmost level
    parent_folder_obj = box.folder(test_folder).__dict__
    selected_parent_folder_obj =\
        box.folder(subfolder_name).parent().parent().__dict__
    assert parent_folder_obj == selected_parent_folder_obj

    # check status2 before append
    status2 = box.folder(subfolder_name).info()
    assert status2['total'] == 0

    # append email to subfolder
    box.folder(subfolder_name).append(text_email2, flags=['flagged'])

    # check status2 after append
    status2 = box.folder(subfolder_name).info()
    assert status2['total'] == 1

    # search non-existent emails
    q = Q()
    query = q.subject('nonEXISTENTemailSEARCHstring')
    emails = box.folder(test_folder).emails(
        query
    )
    assert emails == []

    # search all emails in folder
    emails = box.folder(test_folder).emails()
    assert len(emails) > 0

    # search email 1
    q = Q()
    query = q.subject(test_subject1)
    emails = box.folder(test_folder).emails(
        query
    )
    assert len(emails) > 0
    # add flag to email
    email1 = emails[0]
    email1.mark(['seen', 'unflagged'])

    with pytest.raises(e.TagNotSupported):
        email1.mark(['unsupported_tag', 'really_nonstandard'])

    # check email attributes
    assert 'seen' in email1['flags']
    assert 'flagged' not in email1['flags']
    assert email1['from'] == from1
    assert email1['to'] == to1
    assert email1['subject'] == subject1
    assert email1['text'][0]['text'] == contents1

    # get email flags from server to recheck
    emails_flags = box.folder(test_folder).emails(
        query
    )
    email_flags = emails_flags[0]
    assert 'seen' in email_flags['flags']
    assert 'flagged' not in email_flags['flags']

    # search for email 2
    q = Q()
    query = q.subject(test_subject2)
    emails = box.folder(subfolder_name).emails(
        query
    )
    assert len(emails) > 0

    # check email attributes
    email2 = emails[0]
    assert email2['from'] == from2
    assert email2['to'] == to2
    assert email2['subject'] == subject2
    assert email2['text'][0]['text'] == contents2

    # delete email1 from folder
    email1.delete()
    # check status1 after delete
    status1 = box.folder(test_folder).info()
    assert status1['total'] == 0

    # delete email2 from subfolder
    email2.delete()
    # check status2 after delete
    status2 = box.folder(subfolder_name).info()
    assert status2['total'] == 0

    """

    Copy email

    """
    # append email
    from3 = '*****@*****.**'
    to3 = '*****@*****.**'
    subject3 = 'Copy email testing, заголовок -*-'
    contents3 = 'Testing email copying. Проверка копирования email'

    text_email3 = get_text_email(from3, to3, subject3, contents3)
    box.folder(test_folder).append(text_email3)

    status3 = box.folder(test_folder).info()
    assert status3['total'] == 1

    # copy email
    emails = box.folder(test_folder).emails(-1)
    emails[0].copy(subfolder_name)
    status4 = box.folder(subfolder_name).info()
    assert status4['total'] == 1

    """

    Move email

    """
    from4 = '*****@*****.**'
    to4 = '*****@*****.**'
    subject4 = 'Move email testing'
    contents4 = 'Testing email moving'

    text_email4 = get_text_email(from4, to4, subject4, contents4)
    subfolder_before_move_status = box.folder(subfolder_name).info()
    box.folder(test_folder).append(text_email4)

    emails = box.folder(test_folder).emails(-1)
    assert len(emails) > 0

    emails[0].move(subfolder_name)
    subfolder_after_move_status = box.folder(subfolder_name).info()
    assert subfolder_before_move_status['total'] != \
        subfolder_after_move_status['total']

    """

    Emails selecting

    """
    with pytest.raises(e.InvalidSearchQuery):
            box.folder(test_folder).emails(1, 2, 3)

    with pytest.raises(e.InvalidSearchQuery):
            box.folder(test_folder).emails('something', 'weird')

    with pytest.raises(e.InvalidSearchQuery):
            box.folder(test_folder).emails('weird')

    with pytest.raises(e.InvalidSearchQuery):
            box.folder(test_folder).emails(1, -10)

    with pytest.raises(e.InvalidSearchQuery):
            box.folder(test_folder).emails(-1, 10)

    # test folders searching with regexp
    # setup fake box.mail_folders variable and separator
    box.mail_folders = [
        # level 1
        'Inbox',
        'Some long name',
        'Входящие',
        'Длинное название ящика',
        # level 2
        'Inbox/Important stuff',
        'Входящие/Важные сообщения',
    ]
    box.separator = '/'

    assert 'Inbox' in box.folders('Inbox')
    assert 'Inbox' in box.folders('*nbox')
    assert 'Inbox' in box.folders('Inbo*')
    assert 'Inbox' in box.folders('*nbo*')
    assert 'Inbox' in box.folders('*n*o*')
    assert 'Some long name' in box.folders('Some*long*')
    assert 'Some long name' in box.folders('*o*n*e')
    assert 'Some long name' in box.folders('*long*')
    assert 'Длинное название ящика' in box.folders('*инн*')
    assert 'Длинное название ящика' in box.folders('Длинное*')
    assert 'Длинное название ящика' in box.folders('*ящика')
    assert 'Inbox/Important stuff' in box.folders('Important*')
    assert 'Inbox/Important stuff' in box.folders('*ant*')
    assert 'Inbox/Important stuff' in box.folders('* stuff')
    assert 'Входящие/Важные сообщения' in box.folders('Важные*')
    assert 'Входящие/Важные сообщения' in box.folders('*сообщ*')
    assert 'Входящие/Важные сообщения' in box.folders('* сообщения')

    # log out
    box.log_out()
    with pytest.raises(e.ImapyLoggedOut):
            box.folders()
Ejemplo n.º 14
0
    def recieve_unseen(self, count=5):
        '收取未读的邮箱,这里默认每次只收取5个'

        box = imapy.connect(
            host=self._host,
            port=self._port,
            username=self._username,
            password=self._password,
            ssl=True,
        )

        q = Q()

        emails = box.folder('INBOX').emails(q.unseen())[0:count]

        emails = list(reversed(emails))

        p = re.compile(r'.*#工单流程')

        for mail in emails:
            try:
                # 重新连接数据库
                close_old_connections()

                subject = mail['subject']
                from_email = mail['from_email']
                user = User.objects.get(email=from_email)
                username = user.username
                # 如果匹配到的是工单流程的主题的邮件,则需要处理
                # 如果不是,这里就标记为已读
                if p.match(subject):
                    user = User.objects.get(username=username)
                    wse = subject.split("#")[3].split('=')[
                        1]  # 'Re:#工单流程#剑雨后端SVN申请#wse=92' ==> 92
                    wse = WorkflowStateEvent.objects.get(id=int(wse))
                    reply = mail['text'][0]['text']
                    if reply.startswith('yes'):
                        transition = wse.state.transition.get(condition='同意')
                        ml.logger.info('%s: %s: 同意处理' % (subject, username))

                        msg, success, new_wse = do_transition(
                            wse, transition, user)

                        to_list = [
                            x.email
                            for x in get_state_user(transition.destination,
                                                    obj=new_wse.content_object)
                            if x.email
                        ]

                        if to_list:
                            subject, content = make_email_notify(True)
                            send_mail.delay(to_list, subject, content)
                        ml.logger.info('%s: %s: 处理结果:%s %s' %
                                       (subject, username, msg, success))
                    elif reply.startswith('no'):
                        transition = wse.state.transition.get(condition='拒绝')
                        ml.logger.info('%s: %s: 拒绝处理' % (subject, username))
                        msg, success, new_wse = do_transition(
                            wse, transition, user)

                        to_list = [new_wse.creator.email]
                        subject, content = make_email_notify(False)
                        send_mail.delay(to_list, subject, content)

                        ml.logger.info('%s: %s: 处理结果:%s %s' %
                                       (subject, username, msg, success))
                    else:
                        ml.logger.warn('%s: %s: 没有匹配到指令' % (subject, username))
                else:
                    ml.logger.warn('%s: %s: 没有匹配到主题' % (subject, username))
            except Exception as e:
                ml.logger.error('%s: %s: %s' % (from_email, subject, str(e)))
            finally:
                # 主题邮件全部标记为已读
                mail.mark('Seen')
        box.logout()
Ejemplo n.º 15
0
Archivo: basic.py Proyecto: s0x90/imapy
# -*- encoding: utf-8 -*-
"""
Shows some basic operations with Imapy
"""

import imapy

box = imapy.connect(
    host="host",
    username="******",
    password="******",
    # you may also specify custom port:
    # port=993
    ssl=True,
)

# get all folder names
folders = box.folders()

""" 'folders' now contains a list of all folder names.
    Email folders can be hierarchical (have parent and
    children). A folder name of a child folder consists
    of a parent name + separator symbol + name of a child.
"""

# get information about Inbox folder
# (note that Gmail uses "INBOX" as Inbox folder name)
status = box.folder("Inbox").info()
total_messages = status["total"]

# create folder named 'Awesome' in the root folder
Ejemplo n.º 16
0
import os
import imapy
import pdfkit
from lxml import html
from pprint import pprint
from dateutil import parser
from imapy.query_builder import Q

#Vars
email = '*****@*****.**'
password = '******'
imap_server = 'imap.gmail.com'
emails_since = '27-Oct-2016'
subject = 'Sua viagem de'

box = imapy.connect(host=imap_server,username=email,password=password,ssl=True)
q = Q()

print 'Searching e-mails...'
emails = box.folder('INBOX').emails(q.subject(subject).sender("uber.com").since(emails_since))
print 'Were found %d e-mails' % len(emails)
options = {'quiet': ''}
for email in emails:
    pdf_file = '%s.pdf' % email.uid
    pdf_path = os.path.join('saida',pdf_file)
    print pdf_file
    corpo = email['html'][0].decode('utf-8','ignore')
    try:
        pdfkit.from_string(corpo,pdf_path,options=options)
    except Exception as e:
        print e
Ejemplo n.º 17
0
    db.close()
    logging.debug('Подключение к базе данных проверено')

# проверяем наличие папки images, если нет, то создаем
if not ("images" in os.listdir(path=".")):
    os.mkdir("images", mode=0o777)
    logging.debug('Создана папка images')

# запускаем парсер
while True:
    logging.debug('Парсер почты запущен')
    try:
        # подключение к email
        box = imapy.connect(
            host=host,
            username=user,
            password=password,
            ssl=True,
        )
    except Exception:
        logging.debug('Ошибка подключение к серверу почты')
        break

    # Открываем подключение к базе данных
    db = sqlite3.connect("email.db")
    con = db.cursor()

    # получаем кол-во писем доступных для парсинга
    status = box.folder(INBOX).info()
    total_messages = status['total']

    # получаем почту из папки
Ejemplo n.º 18
0
def mail_connect():
    box = imapy.connect(host=mail_config.HOST,
                        username=mail_config.USERNAME,
                        password=mail_config.PASSWORD,
                        ssl=True)
    return box
Ejemplo n.º 19
0
def main():
    box = imapy.connect(
        host=HOST,
        username=USERNAME,
        password=PASSWORD,
        ssl=True,
    )

    q = Q()

    emails = box.folder('INBOX').emails(
        q.sender("pycoders.com")
    )
    DONE_FOLDER = 'weekly' + box.separator + '1'

    if DONE_FOLDER not in box.folders():
        base, sub = DONE_FOLDER.split(box.separator)
        box.make_folder(base)
        box.folder(base).make_folder(sub)

    print(box.folders())

    with shelve.open('wc.db', writeback=True) as db:
        if 'emails' not in db:
            db['emails'] = {}
        if 'links' not in db:
            db['links'] = set()


    with shelve.open('wc.db', writeback=True) as db:
        for email in emails:
            db['emails'][email['subject']] = {
                'headers': email['headers'],
                'from': email['from'],
                'from_email': email['from_email'],
                'from_whom': email['from_whom'],
                'to': email['to'],
                'flags': email['flags'],
                'subject': email['subject'],
                'cc': email['cc'],
                'date': email['date'],
                'text_normalized': email['text'][0]['text_normalized'],
            }


    for email in emails:
        email.move(DONE_FOLDER)

    with shelve.open('wc.db', writeback=True) as db:
        for subject, email in db['emails'].items():
            links = set(parse_links(email['text_normalized']))
            for email in emails:
                db['links'].update(set(links))



    with shelve.open('wc.db') as db:
        for chunk in chunked(db['links'], 7):  # XXX: 7 is magic ;)
            for link in chunk:
                if (not is_tw_action(link) and not is_instapaper(link) 
                    and not is_unsubscribe(link)):
                    webbrowser.open_new_tab(link)

            con = input('Next batch (Y/n)')
            if con.lower().startswith('n'):
                break
Ejemplo n.º 20
0

def get_ipv4(headers):
    """Returns ip address (v4) from message 'Received' header.
       (ip detection is oversimplified)
    """
    received = headers['Received'].pop()
    match = re.search('(?P<ip>\d+\.\d+\.\d+\.\d+)', received)
    if match:
        return match.group('ip')
    return 'ip not found'


box = imapy.connect(
    host='host',
    username='******',
    password='******',
    ssl=True,
)

# first create some folders in the root email directory
box.folder().make_folder(['Imapy1', 'Imapy2'])

if 'Inbox' in box.folders():
    """
        Copying emails
    """
    # select first 3 emails in 'Inbox' (the oldest ones)
    emails = box.folder('Inbox').emails(1, 3)
    for em in emails:
        # copy each email to 'Imapy1', flagging it and making unseen
        em.copy('Imapy1').mark(['flagged', 'unseen'])
Ejemplo n.º 21
0
# -*- encoding: utf-8 -*-
"""
Shows some basic operations with Imapy
"""

import imapy

box = imapy.connect(
    host='host',
    username='******',
    password='******',
    # you may also specify custom port:
    # port=993
    ssl=True,
)

# get all folder names
folders = box.folders()
""" 'folders' now contains a list of all folder names.
    Email folders can be hierarchical (have parent and
    children). A folder name of a child folder consists
    of a parent name + separator symbol + name of a child.
"""

# get information about Inbox folder
# (note that Gmail uses "INBOX" as Inbox folder name)
status = box.folder('Inbox').info()
total_messages = status['total']

# create folder named 'Awesome' in the root folder
# having subfolder named 'Even awesomer'
Ejemplo n.º 22
0
# -*- encoding: utf-8 -*-
"""
Shows some folder operations with Imapy
"""

import imapy

box = imapy.connect(
    host='host',
    username='******',
    password='******',
    ssl=True,
)

# get all folder names
folders = box.folders()

# Create folder
box.folder().make_folder('Imapy')

# Create subfolders
# (note how you can pass several folder names in a list)
box.folder('Imapy').make_folder(['Imapy subfolder', 'Kamikaze folder'])

# Get list of children names of a folder
children = box.folder('Imapy').children()
for c in children:
    print("{0} is a child of 'Imapy' folder".format(c))

# Rename subfolder
subfolder_name = 'Imapy' + box.separator + 'Imapy subfolder'
Ejemplo n.º 23
0
import imapy
from imapy.query_builder import Q

box = imapy.connect(
    host='server',
    username=input('Username: '******'Password: '******'INBOX').emails(q.unseen())

    # get attachment from newest
    if len(emails):
        email = emails[-1]
        for attachment in email['attachments']:
            data = attachment['data']

            # Mark as seen
            email.mark('seen')
            return data


get_attachments()

# logout
box.logout()
Ejemplo n.º 24
0
from email.mime.text import MIMEText


def get_text_email(sender, recepient, subject, text):
    """Returns email object"""
    msg = MIMEText(text, "plain", "utf-8")
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = recepient

    return msg


box = imapy.connect(
    host='host',
    username='******',
    password='******',
    ssl='ssl',  # True or False
)

'''
    Suppose we need to process automatically new emails in
    'Inbox' folder which contain 'help me' in subject
'''
# find those emails
q = Q()
emails = box.folder('INBOX').emails(
    q.subject('help me').unseen()
)

# connect to SMTP server
user = '******'
Ejemplo n.º 25
0
def test_operations():

    box = imapy.connect(host=host,
                        username=username,
                        password=password,
                        ssl=ssl)

    assert isinstance(box, imap.IMAP)
    assert box.lib in (imaplib.IMAP4_SSL, imaplib.IMAP4, imaplib.IMAP4_stream)

    # folders()
    folders = box.folders()
    assert len(folders) > 0
    for f in folders:
        assert len(f) > 0
    folders2 = box.folders()
    assert folders2 == folders

    # no children
    assert box.children() == []

    # folder()
    assert box.selected_folder is None
    box.folder(folders[0])
    assert box.selected_folder is not None

    # children()
    assert type(box.children()) is list
    with pytest.raises(e.NonexistentFolderError):
        box.folder('NonexistentFolder')
    '''

    Create, rename, delete folder

    '''
    # create list of folders
    folders_list = ['imapy-del1', 'imapy-del2']
    box.folder().make_folder(folders_list)
    for f in folders_list:
        assert f in box.folders()

    box.folder().delete(folders_list)
    for f in folders_list:
        assert f not in box.folders()

    # create folder
    delete_name = 'Imapy-delete'
    box.folder().make_folder(delete_name)
    assert delete_name in box.folders()
    with pytest.raises(e.InvalidFolderName):
        box.make_folder('BadFolder' + box.separator + 'Name')

    # rename
    new_name = delete_name + '123'
    box.folder(delete_name).rename(new_name)
    assert new_name in box.folders()
    # delete
    box.folder().delete(new_name)
    assert (new_name) not in box.folders()
    '''

    Create subfolders, append messages, check messages,
    folder info, email search, mark messages with tags,
    delete messages, select parent folder

    '''
    # create folder (ascii + unicode)
    test_folder = 'Imapy тест 123'
    box.folder().make_folder(test_folder)
    assert test_folder in box.mail_folders

    # create subfolder (ascii + unicode)
    test_subfolder = 'Subfolder 456 тест'
    box.folder(test_folder).make_folder(test_subfolder)
    test_folder_full_name = test_folder + box.separator + test_subfolder
    assert test_folder_full_name in box.mail_folders

    from1 = '*****@*****.**'
    to1 = '*****@*****.**'
    subject1 = 'Email subject заголовок -*-'
    test_subject1 = 'subject'
    contents1 = 'Email contents содержание'

    text_email1 = get_text_email(from1, to1, subject1, contents1)

    # check status1 before append
    status1 = box.folder(test_folder).info()
    assert status1['total'] == 0

    # append email to folder
    non_standard_flags = ['really-non-standard-flag', 'weird-flag']
    box.folder(test_folder).append(text_email1, flags=non_standard_flags)

    with pytest.raises(e.UnknownEmailMessageType):
        box.folder(test_folder).append({'dummy': 'dict'})

    # check status1 after append
    status1 = box.folder(test_folder).info()
    assert status1['total'] == 1

    # check appended email flags
    emails = box.folder(test_folder).emails(-1)
    for f in non_standard_flags:
        assert f not in emails[0]['flags']

    from2 = '*****@*****.**'
    to2 = '*****@*****.**'
    subject2 = 'Email subject 2заголовок2 -*-'
    test_subject2 = 'subject'
    contents2 = 'Email contents содержание2'

    text_email2 = get_text_email(from2, to2, subject2, contents2)

    children = box.folder(test_folder).children()
    subfolder_name = children[0]

    # check parent selection
    parent_folder_obj = box.folder(test_folder).__dict__
    selected_parent_folder_obj = box.folder(subfolder_name).parent().__dict__
    assert parent_folder_obj == selected_parent_folder_obj

    # check parent selection when parent is already on topmost level
    parent_folder_obj = box.folder(test_folder).__dict__
    selected_parent_folder_obj =\
        box.folder(subfolder_name).parent().parent().__dict__
    assert parent_folder_obj == selected_parent_folder_obj

    # check status2 before append
    status2 = box.folder(subfolder_name).info()
    assert status2['total'] == 0

    # append email to subfolder
    box.folder(subfolder_name).append(text_email2, flags=['flagged'])

    # check status2 after append
    status2 = box.folder(subfolder_name).info()
    assert status2['total'] == 1

    # search non-existent emails
    q = Q()
    query = q.subject('nonEXISTENTemailSEARCHstring')
    emails = box.folder(test_folder).emails(query)
    assert emails == []

    # search all emails in folder
    emails = box.folder(test_folder).emails()
    assert len(emails) > 0

    # search email 1
    q = Q()
    query = q.subject(test_subject1)
    emails = box.folder(test_folder).emails(query)
    assert len(emails) > 0
    # add flag to email
    email1 = emails[0]
    email1.mark(['seen', 'unflagged'])

    with pytest.raises(e.TagNotSupported):
        email1.mark(['unsupported_tag', 'really_nonstandard'])

    # check email attributes
    assert 'seen' in email1['flags']
    assert 'flagged' not in email1['flags']
    assert email1['from'] == from1
    assert email1['to'] == to1
    assert email1['subject'] == subject1
    assert email1['text'][0]['text'] == contents1

    # get email flags from server to recheck
    emails_flags = box.folder(test_folder).emails(query)
    email_flags = emails_flags[0]
    assert 'seen' in email_flags['flags']
    assert 'flagged' not in email_flags['flags']

    # search for email 2
    q = Q()
    query = q.subject(test_subject2)
    emails = box.folder(subfolder_name).emails(query)
    assert len(emails) > 0

    # check email attributes
    email2 = emails[0]
    assert email2['from'] == from2
    assert email2['to'] == to2
    assert email2['subject'] == subject2
    assert email2['text'][0]['text'] == contents2

    # delete email1 from folder
    email1.delete()
    # check status1 after delete
    status1 = box.folder(test_folder).info()
    assert status1['total'] == 0

    # delete email2 from subfolder
    email2.delete()
    # check status2 after delete
    status2 = box.folder(subfolder_name).info()
    assert status2['total'] == 0
    """

    Copy email

    """
    # append email
    from3 = '*****@*****.**'
    to3 = '*****@*****.**'
    subject3 = 'Copy email testing, заголовок -*-'
    contents3 = 'Testing email copying. Проверка копирования email'

    text_email3 = get_text_email(from3, to3, subject3, contents3)
    box.folder(test_folder).append(text_email3)

    status3 = box.folder(test_folder).info()
    assert status3['total'] == 1

    # copy email
    emails = box.folder(test_folder).emails(-1)
    emails[0].copy(subfolder_name)
    status4 = box.folder(subfolder_name).info()
    assert status4['total'] == 1
    """

    Move email

    """
    from4 = '*****@*****.**'
    to4 = '*****@*****.**'
    subject4 = 'Move email testing'
    contents4 = 'Testing email moving'

    text_email4 = get_text_email(from4, to4, subject4, contents4)
    subfolder_before_move_status = box.folder(subfolder_name).info()
    box.folder(test_folder).append(text_email4)

    emails = box.folder(test_folder).emails(-1)
    assert len(emails) > 0

    emails[0].move(subfolder_name)
    subfolder_after_move_status = box.folder(subfolder_name).info()
    assert subfolder_before_move_status['total'] != \
        subfolder_after_move_status['total']
    """

    Emails selecting

    """
    with pytest.raises(e.InvalidSearchQuery):
        box.folder(test_folder).emails(1, 2, 3)

    with pytest.raises(e.InvalidSearchQuery):
        box.folder(test_folder).emails('something', 'weird')

    with pytest.raises(e.InvalidSearchQuery):
        box.folder(test_folder).emails('weird')

    with pytest.raises(e.InvalidSearchQuery):
        box.folder(test_folder).emails(1, -10)

    with pytest.raises(e.InvalidSearchQuery):
        box.folder(test_folder).emails(-1, 10)

    # test folders searching with regexp
    # setup fake box.mail_folders variable and separator
    box.mail_folders = [
        # level 1
        'Inbox',
        'Some long name',
        'Входящие',
        'Длинное название ящика',
        # level 2
        'Inbox/Important stuff',
        'Входящие/Важные сообщения',
    ]
    box.separator = '/'

    assert 'Inbox' in box.folders('Inbox')
    assert 'Inbox' in box.folders('*nbox')
    assert 'Inbox' in box.folders('Inbo*')
    assert 'Inbox' in box.folders('*nbo*')
    assert 'Inbox' in box.folders('*n*o*')
    assert 'Some long name' in box.folders('Some*long*')
    assert 'Some long name' in box.folders('*o*n*e')
    assert 'Some long name' in box.folders('*long*')
    assert 'Длинное название ящика' in box.folders('*инн*')
    assert 'Длинное название ящика' in box.folders('Длинное*')
    assert 'Длинное название ящика' in box.folders('*ящика')
    assert 'Inbox/Important stuff' in box.folders('Important*')
    assert 'Inbox/Important stuff' in box.folders('*ant*')
    assert 'Inbox/Important stuff' in box.folders('* stuff')
    assert 'Входящие/Важные сообщения' in box.folders('Важные*')
    assert 'Входящие/Важные сообщения' in box.folders('*сообщ*')
    assert 'Входящие/Важные сообщения' in box.folders('* сообщения')

    # log out
    box.log_out()
    with pytest.raises(e.ImapyLoggedOut):
        box.folders()
Ejemplo n.º 26
0
from email.mime.text import MIMEText


def get_text_email(sender, recepient, subject, text):
    """Returns email object"""
    msg = MIMEText(text, "plain", "utf-8")
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = recepient

    return msg


box = imapy.connect(
    host='host',
    username='******',
    password='******',
    ssl='ssl',  # True or False
)
'''
    Suppose we need to process automatically new emails in
    'Inbox' folder which contain 'help me' in subject
'''
# find those emails
q = Q()
emails = box.folder('INBOX').emails(q.subject('help me').unseen())

# connect to SMTP server
user = '******'
password = '******'
s = smtplib.SMTP("smtp.gmail.com", 587)
s.ehlo()