|
| 1 | +import os |
| 2 | + |
| 3 | +import boto3 |
| 4 | +from botocore.exceptions import BotoCoreError, ClientError |
| 5 | +from fastapi import HTTPException |
| 6 | + |
1 | 7 | from app.interfaces.email_service_provider import IEmailServiceProvider |
2 | 8 |
|
3 | 9 |
|
4 | 10 | class AmazonSESEmailProvider(IEmailServiceProvider): |
5 | | - def __init__(self, aws_access_key: str, aws_secret_key: str): |
6 | | - pass |
7 | | - |
8 | | - # TODO (Mayank, Nov 30th) - Create an email object to pass into this method |
9 | | - def send_email( |
10 | | - self, recipient: str, subject: str, body_html: str, body_text: str |
11 | | - ) -> dict: |
12 | | - pass |
| 11 | + def __init__( |
| 12 | + self, |
| 13 | + aws_access_key: str, |
| 14 | + aws_secret_key: str, |
| 15 | + region: str, |
| 16 | + source_email: str, |
| 17 | + is_sandbox: bool = True, |
| 18 | + ): |
| 19 | + self.source_email = source_email |
| 20 | + self.is_sandbox = is_sandbox |
| 21 | + self.ses_client = boto3.client( |
| 22 | + "ses", |
| 23 | + region_name=region, |
| 24 | + aws_access_key_id=aws_access_key, |
| 25 | + aws_secret_access_key=aws_secret_key, |
| 26 | + ) |
| 27 | + |
| 28 | + def _verify_email(self, email: str): |
| 29 | + if not self.is_sandbox: |
| 30 | + return |
| 31 | + try: |
| 32 | + self.client.verify_email_identity(EmailAddress=email) |
| 33 | + print(f"Verification email sent to {email}.") |
| 34 | + except Exception as e: |
| 35 | + print(f"Failed to verify email: {e}") |
| 36 | + |
| 37 | + def send_email(self, subject: str, recipient: str) -> None: |
| 38 | + try: |
| 39 | + self._verify_email(recipient) |
| 40 | + self.ses_client.send_email( |
| 41 | + Source=self.source_email, |
| 42 | + Destination={"ToAddresses": [recipient]}, |
| 43 | + Message={ |
| 44 | + "Subject": {"Data": subject}, |
| 45 | + "Body": {"Text": {"Data": "Hello, this is a test email!"}}, |
| 46 | + }, |
| 47 | + ) |
| 48 | + except BotoCoreError as e: |
| 49 | + raise HTTPException(status_code=500, detail=f"SES BotoCoreError: {e}") |
| 50 | + except ClientError as e: |
| 51 | + raise HTTPException( |
| 52 | + status_code=500, |
| 53 | + detail=f"SES ClientError: {e.response['Error']['Message']}", |
| 54 | + ) |
| 55 | + |
| 56 | + |
| 57 | +def get_email_service_provider() -> IEmailServiceProvider: |
| 58 | + return AmazonSESEmailProvider( |
| 59 | + aws_access_key=os.getenv("AWS_ACCESS_KEY"), |
| 60 | + aws_secret_key=os.getenv("AWS_SECRET_KEY"), |
| 61 | + region=os.getenv("AWS_REGION"), |
| 62 | + source_email=os.getenv("SES_SOURCE_EMAIL"), |
| 63 | + ) |
0 commit comments