aboutsummaryrefslogtreecommitdiffstats
path: root/app/SendGridAlerter.py
diff options
context:
space:
mode:
authorJan Tuomi <jans.tuomi@gmail.com>2023-09-27 18:30:05 +0300
committerJan Tuomi <jans.tuomi@gmail.com>2023-09-27 18:31:57 +0300
commit5e21128689f909309064025ace4526a330f0e58d (patch)
treeba49f30021ce3e8b1b387fe0aa2141f3dace609d /app/SendGridAlerter.py
parentda9b89d089482354bce0fc95b66f30fd078405b1 (diff)
Specialize EmailAlerter to use SendGrid API
Diffstat (limited to 'app/SendGridAlerter.py')
-rw-r--r--app/SendGridAlerter.py56
1 files changed, 56 insertions, 0 deletions
diff --git a/app/SendGridAlerter.py b/app/SendGridAlerter.py
new file mode 100644
index 0000000..0509a57
--- /dev/null
+++ b/app/SendGridAlerter.py
@@ -0,0 +1,56 @@
+from typing import Any
+import requests
+import traceback
+from datetime import datetime
+from app.AggroConfig import AggroConfigSendGridAlerter
+from dataclasses import asdict
+
+
+class SendGridAlerter:
+ @staticmethod
+ def from_config(config: AggroConfigSendGridAlerter) -> "SendGridAlerter":
+ return SendGridAlerter(**asdict(config))
+
+ def __init__(
+ self,
+ api_token: str,
+ email_from: str,
+ email_to: list[str],
+ ):
+ self.email_from = email_from
+ self.email_to = email_to
+ self.api_token = api_token
+
+ def send_alert(self, text: str):
+ try:
+ now = datetime.now()
+ now_text = now.strftime("%a, %d %b %Y %H:%M:%S +0000")
+ to_lst = [{"email": email} for email in self.email_to]
+ subject = f"Aggro alert on {now_text}"
+ API_URL = "https://api.sendgrid.com/v3/mail/send"
+ data = {
+ "personalizations": [{"to": to_lst}],
+ "from": {"email": self.email_from},
+ "subject": subject,
+ "content": [
+ {
+ "type": "text/plain",
+ "value": text,
+ }
+ ],
+ }
+ r = requests.post(
+ API_URL,
+ data=data,
+ headers={
+ "Authorization": f"Bearer {self.api_token}",
+ "Content-Type": "application/json",
+ },
+ )
+ if r.status_code >= 400:
+ raise Exception(
+ f"[SendGridAlerter] sending alert email via HTTP returned code {r.status_code} and body:\n{r.text}"
+ )
+
+ except:
+ traceback.print_exc()