forked from Sysdeploy/influx-smtp-gateway
95 lines
2.6 KiB
Python
95 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Serve cloud init files
|
|
"""
|
|
|
|
import configparser
|
|
import os
|
|
import json
|
|
import smtplib
|
|
import socket
|
|
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:
|
|
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
|
|
|
|
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
CONFIG = {
|
|
'/include': {
|
|
'tools.staticdir.on': True,
|
|
'tools.staticdir.dir': os.path.join(CURRENT_DIR,
|
|
'data',
|
|
'include'),
|
|
'tools.staticdir.content_types': {
|
|
'yml': 'text/yaml'
|
|
}
|
|
}
|
|
}
|
|
cherrypy.tree.mount(ROOT, config=CONFIG)
|
|
|
|
if hasattr(ENGINE, "signal_handler"):
|
|
ENGINE.signal_handler.subscribe()
|
|
if hasattr(ENGINE, "console_control_handler"):
|
|
ENGINE.console_control_handler.subscribe()
|
|
try:
|
|
ENGINE.start()
|
|
except Exception: # pylint: disable=broad-except
|
|
sys.exit(1)
|
|
else:
|
|
ENGINE.block()
|