File size: 4,092 Bytes
51cfcf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64a85b5
51cfcf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9650be8
 
 
 
64a85b5
51cfcf3
 
 
 
64a85b5
51cfcf3
 
64a85b5
51cfcf3
 
 
64a85b5
 
 
 
 
 
 
 
 
 
51cfcf3
 
 
 
 
 
9650be8
51cfcf3
 
64a85b5
51cfcf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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))