import sys import datetime import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from pathlib import Path import util, config def sendMailOrWriteToFile(SUBJECT: str, BODY: str): try: sendMail(SUBJECT=SUBJECT, BODY=BODY) except Exception as e: print("Error: Could not send mail! Writing to file instead ...", file=sys.stderr) print(e, file=sys.stderr) # Instead, try to save the mail so that the user can read # it later when connected to this computer saveMail(SUBJECT=SUBJECT, BODY=BODY) def sendMail(SUBJECT: str, BODY: str): """ :throws Exception: if mail could not be sent """ FROM = config.getFrom() TO = config.getTo() password = config.getPassword() # Create a secure SSL context context = ssl.create_default_context() host, port = config.getHostAndPort() with smtplib.SMTP_SSL(host=host, port=port, context=context) as server: server.login(FROM, password) message = MIMEMultipart() message["Subject"] = SUBJECT message["From"] = FROM message["To"] = TO message["Bcc"] = TO # Recommended for mass emails # Turn plain/html message_body into plain/html MIMEText objects message.attach(MIMEText(BODY, "plain")) server.sendmail(FROM, TO, message.as_string()) def saveMail(SUBJECT: str, BODY: str): """ This method does NOT throw exceptions """ time = datetime.datetime.now() timeStr = time.strftime('%Y%m%d_%H%M%S') DATE = '=' * 20 + '\n=== date ===\n' + timeStr + '\n' SUBJECT = '=== subject ===\n' + SUBJECT + '\n' try: # append to file; create file if not existent with open(config.getErrorFile(), "a") as f: f.write(DATE) f.write(SUBJECT) f.write(BODY) except Exception as e: print('Error: Could not write to file!', file=sys.stderr) print(e, file=sys.stderr)