def handle(self, *args, **options): def on_message(to, sender, subject, body): # fn = "mymsg_{}.txt".format(get_random_string(5)) # with open(fn, "wb") as f: # f.write(body) # print "written {} bytes to {}.".format(len(body), fn) text, html, images = parse_message(body) msg = add_email(sender, to, subject, text, html, images) # TODO: send confirmation email # TODO: send email to managers inbox = Inbox(on_message, settings.TURTLES_SMTP_PORT, settings.TURTLES_SMTP_HOST) inbox.serve()
def main(): inbox = Inbox() parser = Parser() telegram = TelegramAPI() # Async callback when email is received @inbox.collate def handle(to, sender, body): try: str_body = quopri.decodestring(body) str_body = str_body.decode("ascii", "ignore") except Exception as e: log.plog(e) return # Caltex Singapore's receipt email body for CaltexGO if ("Thank You - Successful Payment (" not in str_body): # Ignore emails if conditions not met # e.g. using a very specific toaddr like [email protected] print(str_body) return try: # Parses the fixed-format email to extract date, refill, cost per litre ddmmyy, refilled, costperlitre = parser.extract_info(str_body) except ParsingException as e: log.plog("{} (sender: {})".format(e, sender)) return try: # Uses Gspread to get previous mileage sheets_api = SheetsAPI() prev_mileage = sheets_api.get_prev_mileage() # Uses Telegram bot to prompt user for current mileage mileage = telegram.prompt_for_mileage(prev_mileage) except ParsingException as e: print(e) return # Uses Gspread to access Google Sheets API to update cells sheets_api = SheetsAPI() sheets_api.update_row(ddmmyy, mileage, refilled, costperlitre) log.plog("update_row: {} {} {} {}".format(ddmmyy, mileage, refilled, costperlitre)) inbox.serve(address='0.0.0.0', port=4467)
# import smtpd # import asyncore # class CustomSMTPServer(smtpd.SMTPServer): # def process_message(self, peer, mailfrom, rcpttos, data): # print 'Receiving message from:', peer # print 'Message addressed from:', mailfrom # print 'Message addressed to :', rcpttos # print 'Message length :', len(data) # return # server = CustomSMTPServer(('127.0.0.1', 1025), None) # asyncore.loop() from inbox import Inbox inbox = Inbox() @inbox.collate def handle(to, sender, subject, body): print sender print to print subject print body # Bind directly. inbox.serve(address='0.0.0.0', port=465)
#!/usr/bin/env python """ Need to install Logbook and inbox to get the smtpsink to work """ from inbox import Inbox PORT = 4467 ADDR = '0.0.0.0' inbox = Inbox() @inbox.collate def handle(*args, **kwargs): outfile = open('email_log', 'a') for arg in args: outfile.write(arg + "\n") for key, arg in kwargs.items(): outfile.write("{0}: {1}".format(key, arg)) outfile.write('*' * 30) # Bind directly. inbox.serve(address=ADDR, port=PORT) print "serving on {0}:{1}".format(ADDR, PORT)
message['received'] = time.strftime( "%Y-%m-%d %H:%M:%S" ) message['content'] = "" message['attachments'] = [] for part in mail.walk(): if part.get_content_maintype() == "multipart": continue if not part.get_filename(): if part.get_content_maintype() == "text": message['content'] += part.get_payload( decode = False ) else: attachment = {} attachment['filename'] = part.get_filename() attachment['type'] = part.get_content_type() payload = part.get_payload( decode = True ) attachment['payload-id'] = storage.store_attachment( payload, part.get_content_type() ) message['attachments'].append( attachment) storage.store_mail( message ) server = HttpServer( '0.0.0.0', 8123, storage ) # Suppress inbox.py's debug messages handle = open('/dev/null', 'wb' ) sys.stderr = handle inbox.serve(address='0.0.0.0', port=4467)
from inbox import Inbox from smtplib import SMTP inbox = Inbox() SMTP_HOST = 'smtp.mydomain.com' SMTP_INBOX = '*****@*****.**' STOP_AT_COUNT = 1 @inbox.collate def handle(to, sender, subject, body): print 'Forwarding Mail' STOP_AT_COUNT += 1 conn = SMTP(SMTP_HOST, 25, 'localhost') conn.ehlo_or_helo_if_needed() conn.sendmail(sender, SMTP_INBOX, body) conn.quit() if STOP_AT_COUNT == 100: print 'Enough is enough. Closing now.' exit() print 'starting server' inbox.serve(address='0.0.0.0', port=25)
from inbox import Inbox from smtplib import SMTP inbox = Inbox() SMTP_HOST = 'localhost:1025' SMTP_USERNAME = '******' SMTP_PASSWORD = '******' body = 'hi' @inbox.collate def handle(to, sender, body): """ Forward a message via an authenticated SMTP connection with starttls. """ conn = SMTP(SMTP_HOST, 25, 'localhost') conn.starttls() conn.ehlo_or_helo_if_needed() conn.login(SMTP_USERNAME, SMTP_PASSWORD) conn.sendmail(sender, to, body) conn.quit() inbox.serve(address='localhost', port=1025)
def upload_to_s3(file, folder, key): conn = boto.connect_s3(config['aws_access_key'], config['aws_secret_key']) bucket = conn.get_bucket(config['s3_bucket']) k = Key(bucket) k.storage_class = 'STANDARD_IA' k.key = folder + '/' + key k.set_contents_from_filename(file.name, headers={'Content-Type': 'image/jpeg'}) return 'https://s3.amazonaws.com/' + config['s3_bucket'] + '/' + k.name def collect_sub_messages(msg, msgs): payload = msg.get_payload() if isinstance(payload, list): for sub_payload in payload: collect_sub_messages(sub_payload, msgs) else: msgs.append(msg) return msgs print """ # # Binding SMTP to Slack Relay on port """ + str(config['port']) + """ # Posting to slack channel '""" + str(config['channel']) + """' # """ # Bind directly. inbox.serve(address='0.0.0.0', port=config['port'])
logger.debug('No discovery in this email.') subject_matcher = SubjectMatcher(smtptrap_memory, myzabbix, host, subject_discovery.host_match) subject_matcher.parse(subject, decoded_body) myzabbix.add('smtp.trap[message]', decoded_body) myzabbix.add('smtp.trap[sender]', sender) myzabbix.add('smtp.trap[subject]', subject) myzabbix.send() if __name__ == '__main__': if args.service: logger.info('Starting') inbox.serve(address=config.server_bind_address, port=int(config.server_bind_port)) elif args.refresh: logger.info('Refreshing discoveries') resend_discovery() elif args.list: last_host, last_key = None, None for host, key, value in Memory().list(): if host != last_host: last_host = host last_key = key else: host = " " * len(last_host) if key != last_key: last_key = key else: key = " " * len(last_key)
#pip install inbox #dasinbox.py 0.0.0.0 4467 from inbox import Inbox inbox = Inbox() @inbox.collate def handle(to, sender, subject, body): ... # Bind directly. inbox.serve(address='0.0.0.0', port=4467) if __name__ == '__main__': inbox.dispatch()
def sendMail(to, subject, msgContext): pLog("Send Server Mail") config = ConfigParser.RawConfigParser() config.read('defaults.cfg') msg = Message(subject, fromaddr=config.get('SendAbuse', 'from'), to=to) if(to!=config.get('SendAbuse', 'from')): msg.bcc = config.get('SendAbuse', 'from') msg.body = msgContext msg.date = time.time() msg.charset = "utf-8" mail = Mail(config.get('SendAbuse', 'server'), port=config.get('SendAbuse', 'port'), username=config.get('SendAbuse', 'user'), password=config.get('SendAbuse', 'pass'),use_tls=False, use_ssl=False, debug_level=None) mail.send(msg) @inbox.collate def handle(to, sender, subject, body): try: return runBasic(to, sender, subject, body) except: pLog("Something go Wrong, Mail sendet") errorStr = str(sys.exc_info()) config = ConfigParser.RawConfigParser() config.read('defaults.cfg') sendMail(sender, "Mail cant not sendet", "Hello, you try to send a Mail, we cant send this Mail because an error appear. Our Team get the Information, please try it again later!") sendMail(config.get('SendAbuse', 'from'), "MailChain Error", "So following error appear:\r\n\r\n"+errorStr) return "550 Something go wrong" # Bind directly. pLog("Start Server") #sendMail("*****@*****.**", "Abuse Mail", "Something go Wrong!") inbox.serve(address='127.0.0.1', port=4467)
# inbox.py instantiates a standalone mail server based in python and calls the handle function # when it receives a new message. We then "handle" the message by saving it's text to a .txt file # and a .json blob file. # # Todo: # Handle encoding better # Figure out how to handle attachments # Stability and watchdogs from inbox import Inbox import time,json #Create the inbox.py object inbox = Inbox() @inbox.collate #Our message handling function def handle(to, sender, subject, body): #Write the components to the .txt file separated by newlines (ok but a little more readable) with open("/home/ubuntu/newspoc/"+sender+"-"+subject+"-"+str(int(time.time()))+".txt","w") as file: file.write(str(to)+"\n") file.write(str(sender)+"\n") file.write(str(subject)+"\n") file.write(body+"\n") #Write the components to the .json file, better for processing later but doesn't solve encoding with open("/home/ubuntu/newspoc/"+sender+"-"+subject+"-"+str(int(time.time()))+".json","w") as jsonfile: jsonfile.write(json.dumps({"to":to,"sender":sender,"subject":subject,"body":body})) #Start the inbox.py server on our local ip address inbox.serve(address='172.31.34.123', port=25)
username=config.get('SendAbuse', 'user'), password=config.get('SendAbuse', 'pass'), use_tls=False, use_ssl=False, debug_level=None) mail.send(msg) @inbox.collate def handle(to, sender, subject, body): try: return runBasic(to, sender, subject, body) except: pLog("Something go Wrong, Mail sendet") errorStr = str(sys.exc_info()) config = ConfigParser.RawConfigParser() config.read('defaults.cfg') sendMail( sender, "Mail cant not sendet", "Hello, you try to send a Mail, we cant send this Mail because an error appear. Our Team get the Information, please try it again later!" ) sendMail(config.get('SendAbuse', 'from'), "MailChain Error", "So following error appear:\r\n\r\n" + errorStr) return "550 Something go wrong" # Bind directly. pLog("Start Server") #sendMail("*****@*****.**", "Abuse Mail", "Something go Wrong!") inbox.serve(address='127.0.0.1', port=4467)
def handle(rawdata, to, sender, subject, mailhtml, mailplain, attachments): # Write new mails to index.html if not os.path.exists("/home/ubuntu/newspoc/index.html"): open("/home/ubuntu/newspoc/index.html", "w").close() with open("/home/ubuntu/newspoc/index.html", "a") as index: file.write("<a href='"+sender+"-"+subject+"-"+str(int(timenow))+"'>"+sender+"-"+subject+"-"+str(int(timenow))+"</a>\n") print "Added "+sender+"-"+subject+"-"+str(int(timenow))+" to index.html" # Write the components to the .html file separated by newlines (ok but a little more readable) with open("/home/ubuntu/newspoc/"+sender+"-"+subject+"-"+str(int(timenow))+".html","w") as file: file.write("TO:\n"+str(to)+"\n") file.write("SENDER:\n"+str(sender)+"\n") file.write("SUBJECT:\n"+str(subject)+"\n") for attachment in attachments: if not attachment == None: file.write("<a href='/newspoc/"+sender+"-"+subject+"-"+str(int(timenow))+"/attachment-"+attachment[2]+"'>ATTACHMENT: "+attachment[2]+"</a>\n') if not mailhtml == None: file.write("HTML:\n"+mailhtml+"\n") if not mailplain == None: file.write("PLAINTEXT:\n"+mailplain+"\n") print "Wrote "+sender+"-"+subject+"-"+str(int(time.time()))+".html" for attachment in attachments: with open("/home/ubuntu/newspoc/"+sender+"-"+subject+"-"+str(int(timenow))+"/attachment-"+attachment[2],"w") as file: file.write(attachment[1]) print "Wrote attachment"+attachment[2] # Write the components to the .json file, better for processing later but doesn't solve encoding with open("/home/ubuntu/newspoc/"+sender+"-"+subject+"-"+str(int(timenow))+"/"+sender+"-"+subject+"-"+str(int(timenow))+".json","w") as jsonfile: jsonfile.write(json.dumps({"rawdata":rawdata, "to":to, "sender":sender, "subject":subject, "mailhtml":mailhtml, "mailplain":mailplain, "attachments":attachments})) print "Wrote "+sender+"-"+subject+"-"+str(int(time.time()))+".json" # Start the inbox.py server on our local ip address inbox.serve(address=localIPAddress, port=25)