def __init__(self, imap, uid): self.uid = "" self.parts = [] self.ct = "" (t, d) = imap.uid("FETCH", uid, "(BODY)") if d[0] is None: raise IMAP4.error('No message with UID "%s" has been found' % uid) self._parse_body_desc(d[0])
class TestRunner(TestCase): def test__signal_handler(self): with patch('processors.runner.Runner.mailbox', new_callable=PropertyMock) as mb, \ self.assertRaises(SystemExit) as context, \ patch('sys.stdout', new=StringIO()) as mock_stdout: mb.return_value.socket.return_value.fileno.return_value = 42 ep = Runner() ep._signal_handler() self.assertEqual('! caught exit signal - farewell\n', mock_stdout.getvalue()) self.assertEqual(context.exception.code, 0) @patch('processors.runner.IMAP4_SSL', MagicMock(side_effect=IMAP4.error())) @patch.dict(os.environ, TestConfig.mock_os_env, clear=True) def test_mail_loop_failed_login(self): with self.assertRaises(SystemExit) as context, \ patch('sys.stdout', new=StringIO()) as mock_stdout: ep = Runner() ep.mail_loop() self.assertEqual('FATAL : login to mailbox failed \n', mock_stdout.getvalue()) self.assertEqual(context.exception.code, 1) @patch('processors.runner.IMAP4_SSL') @patch.dict(os.environ, TestConfig.mock_os_env, clear=True) def test_mail_loop_open_mailbox_failed(self, mock_imaplib): mock_imaplib.return_value.select.return_value = ('KO', 'dummy') with self.assertRaises(SystemExit) as context, \ patch('sys.stdout', new=StringIO()) as mock_stdout: ep = Runner() ep.mail_loop() self.assertEqual(context.exception.code, 1) self.assertEqual('ERROR: Unable to open mailbox KO\n', mock_stdout.getvalue()) @patch('processors.runner.IMAP4_SSL', MagicMock()) @patch('processors.runner.sleep', MagicMock()) @patch('processors.runner.process_mailbox', MagicMock()) @patch.dict(os.environ, TestConfig.mock_os_env, clear=True) def test_mail_loop_success(self): with patch('processors.runner.Runner.mailbox', new_callable=PropertyMock) as mb, \ patch('sys.stdout', new=StringIO()) as mock_stdout: mb.return_value.select.return_value = ('OK', 'dummy') ep = Runner() ep._call_imap_server() self.assertEqual( '> Opening mailbox...\n> Done.\n~ waiting 10 min\n', mock_stdout.getvalue())
def backup_folder(self, folder): print('Backup:', folder) folder_name = '"%s"' % folder resp, info = self.server.select(folder_name) if resp != 'OK': raise IMAP4.error(info) filename = folder.replace('/', '.') + '.mbox' mbox = open(filename, 'w') resp, items = self.server.search(None, "ALL") numbers = items[0].split() for num in numbers: resp, data = self.server.fetch(num, "(BODY.PEEK[])") text = data[0][1].decode('iso-8859-1') message = email.message_from_string(text) mbox.write(message.as_string(unixfrom=True)) mbox.close()
def fetch_email_token(email, email_passwd, imap_server, token_name): date = datetime.datetime.today().strftime("%d-%b-%Y") serving_attempts = 0 while serving_attempts < 10: try: server = IMAP4_SSL(imap_server) server.login(email, email_passwd) server.select() except (IMAP4.abort, IMAP4.error, ConnectionResetError) as err: print('Error while connecting to IMAP:', err) print('Reconnecting...') time.sleep(5) serving_attempts += 1 if serving_attempts == 10: raise IMAP4.error("Bad connection with imap server") time.sleep(15) attempts = 0 mail_body = None while attempts < 20: typ, msgnums = server.search(None, 'UNSEEN SINCE {}'.format(date)) if msgnums[0]: mail_body = server.fetch( msgnums[0].split()[0], '(UID BODY[TEXT])')[1][0][1].decode('utf-8') if "to change the email address" in mail_body: break server.select() time.sleep(15) attempts += 1 if not mail_body: raise Exception('The email with the steam guard code was not found.') if token_name == "guard": guard_code = re.search(r"\n([\d\w]{5})\r", mail_body).group(1).rstrip() print('Email found, guard code:', guard_code) server.logout() return guard_code elif token_name == "link": link = re.search( r'https://store.store.steampowered.com/(\w+?)">'), group() server.logout() return link
def fetch2file(self, imap, part, filename=None): (t, d) = imap.uid("fetch", self.uid, "(BODY.PEEK[%i])" % (part + 1)) if (t != "OK") or (len(d[0]) != 2): raise IMAP4.error("could not retrieve part %s/%i" % (self.uid, part + 1)) msg = d[0][1] msg = base64.decodestring(msg) if filename is None: out_file = os.tmpfile() else: out_file = open(filename, "w+") out_file.write(msg) out_file.seek(0) if filename is None: return out_file else: out_file.close() return None
def raise_imap_error(self): from imaplib import IMAP4 raise IMAP4.error('Unexpected IDLE response')
def IMAPCALL(call_res): (t, d) = call_res if t != "OK": raise IMAP4.error(d[0]) return (t, d)