I am attempting to send an email using a FastAPI background task, but the email is not being sent. There are no errors in the console, and the rest of the code is functioning correctly.
endpoint:
@user_router.post("/register", tags=["Auth"])
async def register(user_data: UserCreate, service: UserService = Depends()):
return await service.register_user(user_data)
register logic and task:
async def register_user(self, data: dict) -> dict:
...
result = await self.crud.create_model(self.INSTANCE, user_data)
task = BackgroundTasks()
task.add_task(self.email.send_email_verification, data.email)
send_email_verification method:
async def send_email_verification(self, email: str):
...
message = MessageSchema(
recipients=[email],
subject="Your email verification link",
body=body,
subtype="html",
)
await self.mail.send_message(message)
Thought maybe the issue was with the email function, so I replaced the task with a simple function to print text to the console. Therefore, the problem is likely related to asynchronous handling.
The issues arises from the fact that BackgroundTasks
is not a parameter of your path operation function. BackgroundTasks
is supposed to work through dependency injection.
Here is how you could adapt your code:
@user_router.post("/register", tags=["Auth"])
async def register(
user_data: UserCreate,
background_tasks: BackgroundTasks,
service: UserService = Depends()
):
return await service.register_user(user_data, background_tasks)
async def register_user(self, data: dict, background_tasks: BackgroundTasks) -> dict:
...
result = await self.crud.create_model(self.INSTANCE, user_data)
background_tasks.add_task(self.email.send_email_verification, data.email)