def mark_seen(): # 连接邮箱服务器 box = mail_connect() q = Q() emails = box.folder('INBOX').emails(q.unseen() #所有的未读邮件 ) # 遍历,标为已读 for email in emails: email.mark(['seen']) box.logout() return "success"
def count(): # 连接邮箱服务器 box = mail_connect() # names = box.folders() # 实例化query_builder q = Q() emails = box.folder('INBOX').emails(q.unseen() #所有的未读邮件 ) box.logout() return len(emails)
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()))))
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 with open('saida.csv','a') as f:
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()
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()
def __init__(self, user_config): self.user_config = user_config self.query_builder = Q() self._login()
def test_query_builder_size_parsing(): # Byte q = Q() q.smaller('3') assert '3' in q.queries # Byte q = Q() q.smaller(10) assert '10' in q.queries # Byte q = Q() q.smaller('3B') assert '3' in q.queries q = Q() q.larger('4Byte') assert '4' in q.queries q = Q() q.smaller('4 Bytes') assert '4' in q.queries # Kb q = Q() q.larger('1kb') assert '1000' in q.queries q = Q() q.smaller('5 kB') assert '5000' in q.queries q = Q() q.larger('5Kilobyte') assert '5000' in q.queries q = Q() q.smaller('5 Kilobytes') assert '5000' in q.queries # Mb q = Q() q.larger('1mb') assert '1000000' in q.queries q = Q() q.smaller('5 MB') assert '5000000' in q.queries q = Q() q.larger('5Megabyte') assert '5000000' in q.queries q = Q() q.smaller('5 Megabytes') assert '5000000' in q.queries # Gb q = Q() q.larger('1 gb') assert '1000000000' in q.queries q = Q() q.smaller('2 GB') assert '2000000000' in q.queries q = Q() q.larger('3Gigabyte') assert '3000000000' in q.queries q = Q() q.smaller('5 gigabytes') assert '5000000000' in q.queries # exceptions q = Q() with pytest.raises(e.SizeParsingError): q.smaller('5 boobabytes') q = Q() with pytest.raises(e.SizeParsingError): q.larger('5.5 GB') q = Q() with pytest.raises(e.SizeParsingError): q.smaller('5 GBKB')
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()
Shows some email search functionality. """ import imapy from imapy.query_builder import Q box = imapy.connect( host='host', username='******', password='******', ssl=True, ) """ Search for unseen emails from Inbox sent from "example.com" with "important" in subject """ q = Q() emails = box.folder('Inbox').emails( q.unseen().sender("example.com").subject("important")) """ Search for flagged emails from Inbox sent since February 15, 2014 """ q = Q() emails = box.folder('Inbox').emails(q.flagged().since('15-Feb-2014')) """ Search for emails having size less than 4 Kilobytes """ q = Q() emails = box.folder('Inbox').emails( q.smaller('4 KB') # Calls below are also OK: # q.smaller('4 Kilobytes')
def get_all_unseen(box): q = Q() emails = box.folder('INBOX').emails( q.subject('Re: ').unseen() ) return emails