import os import base64 import logging import requests # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class SendGridService: def __init__(self): self.api_key = os.getenv('SENDGRID_API_KEY') self.from_email = os.getenv('SENDGRID_FROM_EMAIL', 'noreply@daease.com') if not self.api_key: logger.warning("SendGrid API key not found in environment variables") def send_report(self, to_email, pdf_data, patient_name): """ Send medical report via SendGrid's API Args: to_email (str): Recipient's email address pdf_data (bytes): The PDF report as bytes patient_name (str): Name of the patient Returns: tuple[bool, str]: (success status, message) """ try: # Check if API key is configured if not self.api_key: return False, "Email service not configured. Please contact support." # Encode PDF data as base64 pdf_base64 = base64.b64encode(pdf_data).decode('utf-8') # Create consistent filename safe_name = patient_name.replace(' ', '_').replace(',', '').replace('.', '') pdf_filename = f"medical_report_daease_{safe_name}.pdf" # Prepare email data email_data = { "personalizations": [ { "to": [{"email": to_email}], "subject": f"Medical Report - {patient_name}" } ], "from": {"email": self.from_email}, "content": [ { "type": "text/plain", "value": f"""Dear {patient_name}, Please find attached your medical report from your recent consultation. Note: This report is for informational purposes only and should not be considered as a substitute for professional medical advice. Best regards, Daease Medical Team Email: daease.main@gmail.com """ } ], "attachments": [ { "content": pdf_base64, "type": "application/pdf", "filename": pdf_filename, "disposition": "attachment" } ] } # Send request to SendGrid API response = requests.post( "https://api.sendgrid.com/v3/mail/send", headers={ "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" }, json=email_data ) # Process response if response.status_code == 202: # SendGrid returns 202 when successful logger.info(f"Successfully sent report to {to_email}") return True, "Report sent successfully!" else: logger.error(f"SendGrid API error: Status {response.status_code}, Body: {response.text}") return False, f"Failed to send email (Error {response.status_code})" except requests.exceptions.RequestException as e: logger.error(f"Request error: {str(e)}") return False, f"Connection error: {str(e)}" except Exception as e: logger.error(f"Unexpected error: {str(e)}") return False, "An unexpected error occurred. Please try again later." @staticmethod def validate_email(email): """ Basic email validation Args: email (str): Email address to validate Returns: bool: True if valid email format """ import re pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' return bool(re.match(pattern, email))