|
| 1 | +import datetime |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import smtplib |
| 5 | +import ssl |
| 6 | +from email.mime.multipart import MIMEMultipart |
| 7 | +from email.mime.text import MIMEText |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +def _send_email(errors: list[dict[str, str]]) -> None: |
| 13 | + SMTP_HOST = os.environ["NOTIFICATIONS_SMTP_HOST"] |
| 14 | + SMTP_PORT = int(os.environ["NOTIFICATIONS_SMTP_PORT"]) |
| 15 | + SMTP_SSL_ENABLED = int(os.environ["NOTIFICATIONS_SMTP_SSL_ENABLED"]) |
| 16 | + SENDER_EMAIL = os.environ["NOTIFICATIONS_SENDER_EMAIL"] |
| 17 | + RECEIVER_EMAIL = os.environ["NOTIFICATIONS_RECEIVER_EMAIL"] |
| 18 | + logger.info(f"Sending email to {RECEIVER_EMAIL}") |
| 19 | + with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server: |
| 20 | + if SMTP_SSL_ENABLED: |
| 21 | + context = ssl.create_default_context() |
| 22 | + server.starttls(context=context) |
| 23 | + message = MIMEMultipart() |
| 24 | + message["Subject"] = "Errors in OC4IDS Datastore Pipeline run" |
| 25 | + message["From"] = SENDER_EMAIL |
| 26 | + message["To"] = RECEIVER_EMAIL |
| 27 | + |
| 28 | + html = f"""\ |
| 29 | + <h1>Errors in OC4IDS Datastore Pipeline run</h1> |
| 30 | + <p>The pipeline completed at {datetime.datetime.now(datetime.UTC)}.</p> |
| 31 | + <p>Please see errors for each dataset below:</p> |
| 32 | + {"".join([ |
| 33 | + f""" |
| 34 | + <h2>{error["dataset_id"]}</h2> |
| 35 | + <p>Source URL: <code>{error["source_url"]}</code></p> |
| 36 | + <pre><code>{error["message"]}</code></pre> |
| 37 | + """ |
| 38 | + for error in errors |
| 39 | + ])} |
| 40 | + """ |
| 41 | + message.attach(MIMEText(html, "html")) |
| 42 | + |
| 43 | + server.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, message.as_string()) |
| 44 | + |
| 45 | + |
| 46 | +def send_notification(errors: list[dict[str, str]]) -> None: |
| 47 | + NOTIFICATIONS_ENABLED = bool(int(os.environ.get("NOTIFICATIONS_ENABLED", "0"))) |
| 48 | + if NOTIFICATIONS_ENABLED: |
| 49 | + _send_email(errors) |
| 50 | + else: |
| 51 | + logger.info("Notifications are disabled, skipping") |
0 commit comments