61 lines
2.3 KiB
Python
61 lines
2.3 KiB
Python
import smtplib
|
|
import traceback
|
|
from email.message import EmailMessage
|
|
from logging.handlers import SMTPHandler
|
|
from typing import List, Union
|
|
|
|
from backend import Config
|
|
|
|
|
|
def send_mail(subject: str, msg_body: str, to_mail: List, from_mail: str = Config.FROM_MAIL):
|
|
subject = subject.strip().replace("\r", "").split("\n")[0] # remove breaks resp. cut after line break
|
|
try:
|
|
msg = EmailMessage()
|
|
msg.set_content(msg_body)
|
|
msg["Subject"] = subject
|
|
msg["From"] = from_mail
|
|
msg["To"] = to_mail
|
|
s = smtplib.SMTP(Config.SMTP_SERVER)
|
|
s.send_message(msg)
|
|
s.quit()
|
|
except Exception as e:
|
|
print(
|
|
"Could not send E-Mail (Exception: {})".format(str(e)))
|
|
|
|
|
|
def send_error_mail(message_or_exception: Union[str, Exception], subject: str = None,
|
|
subject_prefix: str = "[LRC] Error: ",
|
|
receiver_mail_addresses=Config.ERROR_E_MAIL_TO):
|
|
if isinstance(message_or_exception, Exception):
|
|
if subject is None:
|
|
subject = subject_prefix + str(type(message_or_exception))
|
|
else:
|
|
subject = subject_prefix + subject
|
|
msg_body = str(type(message_or_exception)) + ": " + str(message_or_exception) + "\n\n" + traceback.format_exc()
|
|
else:
|
|
if subject is None:
|
|
subject = str(message_or_exception)
|
|
else:
|
|
subject = subject_prefix + subject
|
|
msg_body = str(message_or_exception)
|
|
|
|
send_mail(subject, msg_body, receiver_mail_addresses)
|
|
|
|
|
|
def send_warning_mail():
|
|
pass
|
|
|
|
|
|
def get_smtp_default_handler(receiver_mail_addresses=Config.ADMIN_E_MAIL_TO, subject: str = None,
|
|
subject_prefix: str = "[LRC] Log: "):
|
|
|
|
subject = subject if subject.startswith("[LRC]") else subject_prefix + subject
|
|
return SMTPHandler(Config.SMTP_SERVER, Config.FROM_MAIL, receiver_mail_addresses, subject)
|
|
|
|
|
|
def get_smtp_error_handler(receiver_mail_addresses=Config.ERROR_E_MAIL_TO, subject: str = None,
|
|
subject_prefix: str = "[LRC] Error: "):
|
|
|
|
subject = subject if subject.startswith("[LRC]") else subject_prefix + subject
|
|
return SMTPHandler(Config.SMTP_SERVER, Config.FROM_MAIL, receiver_mail_addresses, subject)
|