forked from Sysdeploy/influx-smtp-gateway
77 lines
2.0 KiB
Python
77 lines
2.0 KiB
Python
#!/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=SERVER_HOST, port=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()
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
SERVER_HOST = os.environ["server_host"]
|
|
SERVER_PORT = 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 KeyError:
|
|
raise KeyError("Please check missing environment variables: to_mail, "
|
|
"from_mail, from_mail_password")
|
|
|
|
cherrypy.server.socket_host = "0.0.0.0"
|
|
cherrypy.server.socket_port = 8081
|
|
ENGINE = cherrypy.engine
|
|
|
|
cherrypy.tree.mount(ROOT, config={})
|
|
|
|
try:
|
|
ENGINE.start()
|
|
except Exception: # pylint: disable=broad-except
|
|
sys.exit(1)
|
|
else:
|
|
ENGINE.block()
|