# db-manager - Builds and manages an OwlBoard database instance - To be run on a # cron schedule # Copyright (C) 2023 Frederick Boniface # This program is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this # program. If not, see # https://git.fjla.uk/OwlBoard/db-manager/src/branch/main/LICENSE import email, smtplib, ssl, os from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate import logger as log smtpHost = os.getenv("OWL_EML_HOST") smtpPort = os.getenv("OWL_EML_PORT") smtpUser = os.getenv("OWL_EML_USER") smtpPass = os.getenv("OWL_EML_PASS") smtpFrom = os.getenv("OWL_EML_FROM") log.out("mailer.py: Mailer module loaded", "DBUG") def submitLogs(retry :bool = False): if retry: log.out("mailer.submitLogs: Retrying fetch and send") text :str = fetchLogs() sendMail(text, retry) def fetchLogs(): with open("dbman-log", "r") as tmpfile: return tmpfile.read() def tidyWorkingFiles(): if os.path.exists("dbman-log"): os.remove("dbman-log") print("Tidied log file") if os.path.exists("cif_data"): os.remove("cif_data") print("Removed cif_data file") if os.path.exists("gw.yaml"): os.remove("gw.yaml") print("Tidied PIS Data") if os.path.exists("reasoncodes.json"): os.remove("reasoncodes.json") print("Tidies reason code data") def sendMail(msg_body :str, retry): message = MIMEMultipart() message['From'] = smtpFrom message['To'] = "server-notification-receipt@fjla.uk" message['Subject'] = "OwlBoard - dbmanager Logs" message['Date'] = formatdate(localtime = True) filename = "cif_data" message.attach(MIMEText(msg_body, "plain")) if os.path.exists(filename): with open(filename, "rb") as attachment: part = MIMEBase("text", "plain") part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header( "Content-Disposition", f"attachment; filename= {filename}", ) message.attach(part) text = message.as_string() context = ssl.create_default_context() try: with smtplib.SMTP(smtpHost, smtpPort) as server: server.starttls(context=context) server.login(smtpUser, smtpPass) server.sendmail(smtpFrom, "server-notification-receipt@fjla.uk", text) except Exception as e: log.out(f"mailer.sendMail: Error sending message: {e}", "EROR") if not retry: os.remove("cif_data") log.out("mailer.sendMail: Removing CIF Data to shrink email size") submitLogs(retry = True) else: print("Error retrying to mail logs, giving up") finally: tidyWorkingFiles()