sabuhish / fastapi-mail

Fastapi mail system sending mails(individual, bulk) attachments(individual, bulk)
https://sabuhish.github.io/fastapi-mail/
MIT License
698 stars 81 forks source link

coroutine was never awaited error #154

Closed marc-odp closed 1 year ago

marc-odp commented 2 years ago

Hi, I created a function like this

async def email_simple_send() -> JSONResponse:
    email = EmailSchema(email=['info@website.com'])
    html = """<p>Hi this test mail, thanks for using Fastapi-mail</p> """
    message = MessageSchema(
        subject="Test",
        recipients=email.dict().get("email"),
        body=html,
        subtype=MessageType.html)  # subtype=MessageType.plain
    fm = FastMail(conf)
    # fm.send_message(message, template_name='email.html')
    await fm.send_message(message)
    return JSONResponse(status_code=200, content={"message": "email has been sent"})

How am I supposed to call it ? I tried this

def main():
    email_simple_send()
    return None

if __name__ == "__main__":
    main()

But I get this error

RuntimeWarning: coroutine 'email_simple_send' was never awaited  email_simple_send()

Any idea ? Thanks.

ramiswailem commented 2 years ago

def main(): await email_simple_send() return None

marc-odp commented 2 years ago

I tried that but I get the error

await email_simple_send()
    ^
SyntaxError: 'await' outside async function
ramiswailem commented 2 years ago

You need to make the "main" function async

async def main():

marc-odp commented 2 years ago
async def main():    
    await email_simple_send()    
    return None

if __name__ == "__main__":
    main()

Gives : RuntimeWarning: coroutine 'main' was never awaited main()

And this

async def main():    
    await email_simple_send()    
    return None

if __name__ == "__main__":
   await main()

Gives :

    await main()
    ^
SyntaxError: 'await' outside function

So it seems that we are out of solution at this point. That doesn't seem right, is it ?

ramiswailem commented 1 year ago

Can You please do it with this code:

import asyncio

if __name__ == "__main__":
    asyncio.run(main())
marc-odp commented 1 year ago

I did it like this and it worked perfectly. Thank you for your help ! All the examples in the doc are "routes" examples. Maybe it would be good to add one example to show how to use the library this way too ?

def main():
    asyncio.run(email_simple_send())
    return None

if __name__ == "__main__":
    main()