#!/usr/bin/env python3 """ Serve cloud init files """ import os import json import smtplib import sys from email.header import Header from email.mime.text import MIMEText import cherrypy class CloudInitApp: """ Serve cloud init files """ def _send_mail(self): try: # pylint: disable=deprecated-lambda 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('smtp.gmail.com') 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): """ v1 api endpoint user-data """ return self._send_mail() ROOT = CloudInitApp() if __name__ == "__main__": try: SERVER_HOST = os.environ["server_host"] SERVER_PORT = int(os.environ["server_port"]) TO_MAIL = os.environ["to_mail"] FROM_MAIL = os.environ["from_mail"] FROM_MAIL_PASSWORD = os.environ["from_mail_password"] except: # noqa:E722 raise "Please check missing environment variables: to_mail, from_mail, \ from_mail_password" cherrypy.server.socket_host = SERVER_HOST cherrypy.server.socket_port = 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()