Before we jump in into sending emails, let us first see some pros, cons of using Brevo (SendInBlue). Also, please note that in no way, Sendinblue sponser me 😔.
Pros:
- Quick Setup
- Minimal Code (for simple transactional emails)
Cons:
- Documentation can be significantly improved :(
Let's install some requirements first with pip install -r requirements.txt
fastapi==0.101.1
uvicorn==0.23.2
python-dotenv==1.0.0
requests==2.31.0
Let's jumpstart on integrating Brevo with FastAPI. I would like to create a generic service first that can be consumed with Python. And then simply call the function in our fastapi route.
import requests
import json
from config import settings
def send_email(to_email: str, subject: str, text_content: str):
url = "https://api.brevo.com/v3/smtp/email"
payload = json.dumps(
{
"sender": {"name": "Sourabh", "email": settings.EMAIL_FROM},
"to": [{"email": f"{to_email}"}],
"subject": subject,
"textContent": text_content,
}
)
headers = {
"accept": "application/json",
"api-key": settings.BREVO_API_KEY,
"content-type": "application/json",
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
Yup, that's it, this piece of code is sufficient to send a simple transactional email. We would also require a file where we can store our configuration variables. It can be a config.py file that reads configurations from a .env file.
import os
from dotenv import load_dotenv
from pathlib import Path
env_path = Path(".") / ".env"
load_dotenv(dotenv_path=env_path)
class Settings:
EMAIL_FROM = os.getenv("EMAIL_FROM","ping@fastapitutorial.com")
BREVO_API_KEY: str = os.getenv("BREVO_API_KEY")
settings = Settings()
Obviously, we would need the .env file to have the secrets. The .env file is below:
BREVO_API_KEY=xkeysib-watchtheseanimes:dororo|opm|deathnote|andAOTforsure
Almost, there, We need to plug the send_mail to our main.py file.
from fastapi import FastAPI
from services.brevo import send_email
app = FastAPI()
@app.get("/")
async def root():
send_email(
to_email="youremail@gmail.com",
subject="Is Python SDK work done?",
text_content="Hi Sourabh,\nIs Python SDK work complete or not?")
return {"message": "Hello World"}
Now, if you visit: 127.0.0.1:8000, You should receive mail, also the terminal would say something just like this
INFO: Started server process [23844]
INFO: Waiting for application startup.
INFO: Application startup complete.
{"messageId":"<202310270744.59296368596@smtp-relay.mailin.fr>"}