#!/usr/bin/env python3 """ SMTP webhook server """ import os import json import smtplib import sys from email.header import Header from email.mime.text import MIMEText import cherrypy class SMTPWebhookApp: """ SMTP webhook server """ def _send_mail(self): try: cl = cherrypy.request.headers['Content-Length'] rawbody = cherrypy.request.body.read(int(cl)) req_body = json.loads(rawbody) subject = req_body['subject'] body = req_body['body'] client = smtplib.SMTP(host=SMTP_SERVER_HOST, port=SMTP_SERVER_PORT) msg = MIMEText(body, 'plain', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = FROM_MAIL msg['To'] = TO_MAIL client.ehlo() client.starttls() client.ehlo() client.login(msg["From"], FROM_MAIL_PASSWORD) client.sendmail(msg['From'], msg['To'], msg.as_string()) client.quit() return "mail sent successfully" except Exception as e: return "some error: {}".format(e) @cherrypy.expose def send_mail(self): """ api endpoint for send mail """ return self._send_mail() ROOT = SMTPWebhookApp() SMTP_SERVER_PORT = 587 CHERRYPY_SERVER_HOST = "0.0.0.0" CHERRYPY_SERVER_PORT = 8081 if __name__ == "__main__": try: SMTP_SERVER_HOST = os.environ["smtp_server_host"] TO_MAIL = os.environ["to_mail"] FROM_MAIL = os.environ["from_mail"] FROM_MAIL_PASSWORD = os.environ["from_mail_password"] except KeyError: raise KeyError("Please check missing environment variables: to_mail, " "from_mail, from_mail_password") cherrypy.server.socket_host = CHERRYPY_SERVER_HOST cherrypy.server.socket_port = CHERRYPY_SERVER_PORT ENGINE = cherrypy.engine cherrypy.tree.mount(ROOT, config={}) try: ENGINE.start() except Exception: # pylint: disable=broad-except sys.exit(1) else: ENGINE.block()