fraud-detector-app / alerts.py
soupstick's picture
Initial commit: HF Spaces Fraud Detector scaffold
3595d5c
import os
import smtplib
from email.message import EmailMessage
import requests
SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY", "")
EMAIL_USER = os.getenv("EMAIL_USER", "")
EMAIL_PASS = os.getenv("EMAIL_PASS", "")
EMAIL_HOST = os.getenv("EMAIL_HOST", "smtp.gmail.com")
EMAIL_PORT = int(os.getenv("EMAIL_PORT", 587))
SLACK_WEBHOOK = os.getenv("SLACK_WEBHOOK", "")
ADMIN_EMAIL = os.getenv("ADMIN_EMAIL", "")
class EmailNotifier:
def __init__(self):
pass
def send_alert(self, recipient: str, subject: str, body: str, attachment: str = None) -> bool:
if SENDGRID_API_KEY:
try:
import sendgrid
from sendgrid.helpers.mail import Mail, Attachment, FileContent, FileName, FileType, Disposition
sg = sendgrid.SendGridAPIClient(SENDGRID_API_KEY)
message = Mail(from_email=EMAIL_USER or "noreply@example.com", to_emails=recipient, subject=subject, plain_text_content=body)
if attachment and os.path.exists(attachment):
with open(attachment, "rb") as f:
data = f.read()
import base64
encoded = base64.b64encode(data).decode()
attachedFile = Attachment(FileContent(encoded), FileName(os.path.basename(attachment)), FileType("application/pdf"), Disposition("attachment"))
message.attachment = attachedFile
sg.send(message)
return True
except Exception as e:
print("SendGrid error:", e)
try:
msg = EmailMessage()
msg["Subject"] = subject
msg["From"] = EMAIL_USER or "noreply@example.com"
msg["To"] = recipient
msg.set_content(body)
if attachment and os.path.exists(attachment):
with open(attachment, "rb") as f:
data = f.read()
msg.add_attachment(data, maintype="application", subtype="pdf", filename=os.path.basename(attachment))
with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) as server:
server.starttls()
if EMAIL_USER and EMAIL_PASS:
server.login(EMAIL_USER, EMAIL_PASS)
server.send_message(msg)
return True
except Exception as e:
print("SMTP send error:", e)
return False
class SlackNotifier:
def __init__(self, webhook_url: str):
self.webhook = webhook_url
def send(self, text: str):
if not self.webhook:
return False
try:
requests.post(self.webhook, json={"text": text}, timeout=10)
return True
except Exception as e:
print("Slack send error:", e)
return False