Again, let's first review the pros and cons like the previous tutorial with Brevo.
Pros:
- super scalable
Cons:
- Time to get started is higher.
- Lots of too and fro of messages between the customer support of SES before going to production.
tell us how often you send email, how you maintain your recipient lists, and how you manage bounces, complaints, and unsubscribe requests. It is also helpful to provide examples of the email you plan to send so we can ensure that you are sending high-quality content that recipients will want to receive.
Okay, It's up to you to decide. But if want to go with AWS SES, here is a guide. Let us first install the requirements:
fastapi==0.101.1
uvicorn==0.23.2
python-dotenv==1.0.0
boto3==1.28.57
botocore==1.31.57
Once the requirements are installed, Go to AWS SNS, go to verified identities, and create 2 new identities. Make sure you download the ses key information.
Make sure you verify your identity by clicking on the link that you receive in your email, then your ses dashboard should look like:
Once this is done, put the secrets in a .env file.
[email protected]
AWS_USER=fastapiuser
AWS_SES_REGION=ap-south-1
AWS_ACCESS_KEY=take|some|rest
AWS_SECRET_KEY=dont|burn|out
Then let's create a service to communicate and email with the help of SES. service/ses.py
import os
import boto3
from botocore.exceptions import ClientError
from dotenv import load_dotenv
from pathlib import Path
env_path = Path(".") / ".env"
load_dotenv(dotenv_path=env_path)
class EmailService:
def __init__(self):
self.ses = boto3.client(
"ses",
region_name=os.getenv("AWS_SES_REGION"),
aws_access_key_id=os.getenv("AWS_ACCESS_KEY"),
aws_secret_access_key=os.getenv("AWS_SECRET_KEY"),
)
self.sender_email = os.getenv("AWS_SES_VERIFIED_MAIL")
def send_email(self, to_email: str, subject: str, message: str):
try:
response = self.ses.send_email(
Source=self.sender_email,
Destination={"ToAddresses": [to_email]},
Message={
"Subject": {"Data": subject},
"Body": {"Text": {"Data": message}},
},
)
print(response["MessageId"])
return response["MessageId"]
except ClientError as e:
raise Exception(f"Email sending failed: {str(e)}")
Finally, let's have our main.py file to send a fastapi request and ignite ses.
from fastapi import FastAPI
from services.ses import EmailService
app = FastAPI()
@app.get("/ses/")
async def root():
EmailService().send_email(
to_email="[email protected]",
subject="Is Python SDK work done?",
message="Hi Sourabh\nIs Python SDK work complete or not?")
return {"message": "Mail Sent"}
If you don't get any exception, You should definitely receive a mail like below:
Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.
We know, we might make it hard for you but definitely worth the efforts.
© Copyright 2022-23 Team FastAPITutorial