Skip to content

Background Task in FastAPI Blocks Execution Despite Using BackgroundTasks #221

Open
@Jay-fly

Description

@Jay-fly

Description:

When adding a background task to FastAPI’s BackgroundTasks, the execution of the task still blocks the main thread or API request. This issue persists even though the task is correctly added to BackgroundTasks.

Environment:

• FastAPI Version: 0.112.1
• FastAPI-Mail Version: 1.4.1
• Python Version: 3.10
• SMTP Server: Mailpit (running in Docker)
• Operating System: macOS Sequoia 15.0.1 (Apple M1)

Api Code

from fastapi import BackgroundTasks, FastAPI
from fastapi_mail import ConnectionConfig, FastMail, MessageSchema, MessageType

app = FastAPI()


@app.get("/send-mail")
async def send_mail(background_tasks: BackgroundTasks):
    message = MessageSchema(
        subject="Hello World",
        recipients=["[email protected]"],
        body="This is a test email",
        subtype=MessageType.plain,
    )

    conf = ConnectionConfig(
        MAIL_USERNAME="",
        MAIL_PASSWORD="",
        MAIL_PORT=1025,
        MAIL_SERVER="localhost",
        MAIL_STARTTLS=False,
        MAIL_SSL_TLS=False,
        MAIL_DEBUG=False,
        MAIL_FROM="[email protected]",
        USE_CREDENTIALS=False,
    )

    fm = FastMail(conf)

    # Adding to background task
    background_tasks.add_task(fm.send_message, message)
    return {"message": "Mail sent"}

this is a test api

@app.get("/test")
def test():

    return {"message": "Hello World"}
2024-12-17.6.07.31.mov

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions