fastapi-mail: send_message as background task is not working

Mails are not going out in background.

We have backgrounds tasks working well in other endpoints. Any idea of what could be the issue?

We tried without a template (exactly like your example) and it does not work either.

class SigninEmailSchema(BaseModel):
    recipient: EmailStr
    a: str
    b: str


@router.post('/email/signin')
async def send_signin_email(
        bg: BackgroundTasks,
        contents: SigninEmailSchema,
    ) -> JSONResponse:

    message = MessageSchema(
        subject = ' subject ',
        recipients = [contents.recipient],
        template_body = {
            'a': contents.a,
            'b': contents.b,
        },
    )

    fm = FastMail(conf)

    #await fm.send_message(message, template_name='signin.html') # WORKS
    bg.add_task(fm.send_message, message, template_name='signin.html') # DOES NOT WORK

    return JSONResponse(
        status_code=200,
        content = {'message': 'email was sent'},
)

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 21 (5 by maintainers)

Most upvoted comments

The code I have is exactly what I wrote above (1st comment). Note the line that works (with await) and the one that does not (with add_task)

locally I run it with uvicorn app.main:app --reload in production I have it on heroku with uvicorn app.main:app --host=0.0.0.0 --port=${PORT:-5000}

I was on 1.0.6. I tried it now with 1.0.9 and it’s still the same. What about you @AlparslanKaraguney ?