Files
Inventarsystem/Web/modules/emailservice/email.py
T

98 lines
2.8 KiB
Python

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import time
import Web.modules.database.settings as cfg
def _build_smtp_client():
smtp = smtplib.SMTP(
cfg.EMAIL_SMTP_HOST,
cfg.EMAIL_SMTP_PORT,
timeout=cfg.EMAIL_TIMEOUT_SECONDS,
)
smtp.ehlo()
if cfg.EMAIL_USE_TLS:
smtp.starttls()
smtp.ehlo()
if cfg.EMAIL_USERNAME:
smtp.login(cfg.EMAIL_USERNAME, cfg.EMAIL_PASSWORD or "")
return smtp
def send(email: list | str, subject: str, note: str, sender: str) -> bool:
"""Sends the email with the link to the Clients."""
if not cfg.MODULES.is_enabled("mail"):
print("Debug: Module not enabled")
return False
if isinstance(email, str):
email = [email]
body_message = note
HTML_SIGNATURE = f"""
<table cellpadding="0" cellspacing="0" border="0" style="font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #333333; line-height: 1.5;">
<tr>
<td>
<p style="margin:0 0 12px 0;">Mit freundlichen Grüßen</p>
<p style="margin:0;"><strong style="font-size:16px;">Automatisierter Email Verteiler für die Schule: {cfg.get_school_info().get("name")}</strong><br></p>
<p style="margin:12px 0 0 0;"><strong>Invario UG</strong><br>Am Sportplatz 10<br>83052 Bruckmühl</p>
</td>
</tr>
</table>
"""
text_content = f"{body_message}\n\nMit freundlichen Grüßen\n{sender}\nInvario UG"
html_content = f"""
<html>
<body>
<p>{body_message}</p>
<br>
{HTML_SIGNATURE}
</body>
</html>
"""
mails_per_second = 10
interval = 1.0 / mails_per_second
smtp = None
try:
smtp = _build_smtp_client()
for i, recipient in enumerate(email):
start_time = time.time()
msg = MIMEMultipart("alternative")
msg["Subject"] = str(subject)
msg["From"] = f"{sender} <{cfg.EMAIL_USERNAME}>"
msg["To"] = str(recipient)
msg.attach(MIMEText(text_content, "plain"))
msg.attach(MIMEText(html_content, "html"))
smtp.sendmail(
from_addr=cfg.EMAIL_USERNAME,
to_addrs=[recipient],
msg=msg.as_string()
)
elapsed_time = time.time() - start_time
sleep_time = interval - elapsed_time
if sleep_time > 0 and i < len(email) - 1:
time.sleep(sleep_time)
return True
except Exception as e:
print(f"Debug: Fehler beim Senden der E-Mail: {e}")
return False
finally:
if smtp:
try:
smtp.quit()
except Exception:
pass