exec-notify/execNotifyDir/mail.py
2020-12-26 15:15:54 +01:00

87 lines
2.5 KiB
Python

import sys
import datetime
import smtplib, ssl
import socket
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from execNotifyDir import 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)
def prevMailNotSent():
return config.getErrorFile().exists()
def informAboutOldMail():
"""
Try to inform user via mail about previous error(s) that could not be sent to him before.
Maybe this time sending of an email works ;)
"""
SUBJECT = '{} | Some mails not sent!'.format(socket.gethostname())
BODY = 'Please check the file {} for mails which could previously not be sent to you!\n' \
'Note: You may delete the file after reading it ;)' \
.format(config.getErrorFile())
sendMail(SUBJECT=SUBJECT, BODY=BODY)