I am using fastapi-mail to send a simple email from backend for one of the routes. This is the code that I have running:
from fastapi import FastAPI
from starlette.responses import JSONResponse
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig, MessageType
from pydantic import EmailStr, BaseModel
router = APIRouter(
prefix="/model_flow_notification_and_status",
tags=["model_flow_notification_and_status"],
# dependencies=[Depends(is_access_token_valid)],
responses={
404: {"description": "Not found"}
},
)
conf = ConnectionConfig(
MAIL_USERNAME='[email protected]',
MAIL_PASSWORD="aaaa aaaa aaaa aaaa", #2FA enabled on gmail and this is a valid app password
MAIL_FROM='[email protected]',
MAIL_PORT=587,
MAIL_SERVER="smtp.gmail.com",
MAIL_STARTTLS=False,
MAIL_SSL_TLS=False,
USE_CREDENTIALS=True,
VALIDATE_CERTS=True
)
@router.post("/email")
async def simple_send(email: EmailSchema) -> JSONResponse:
html = """<p>Hi this test mail, thanks for using Fastapi-mail</p> """
message = MessageSchema(
subject="Fastapi-Mail module",
recipients=email.dict().get("email"),
body=html,
subtype=MessageType.html)
fm = FastMail(conf)
await fm.send_message(message)
return JSONResponse(status_code=200, content={"message": "email has been sent"})
But I get this error once I call my API (after some 30 seconds):
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 1041, in create_connection
sock = await self._connect_sock(
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 955, in _connect_sock
await self.sock_connect(sock, address)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/selector_events.py", line 502, in sock_connect
return await fut
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py", line 492, in wait_for
fut.result()
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/aiosmtplib/smtp.py", line 500, in _create_connection
transport, _ = await asyncio.wait_for(connect_coro, timeout=self.timeout)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py", line 494, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/fastapi_mail/connection.py", line 45, in _configure_connection
await self.session.connect()
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/aiosmtplib/smtp.py", line 449, in connect
raise exc
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/aiosmtplib/smtp.py", line 446, in connect
response = await self._create_connection()
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/aiosmtplib/smtp.py", line 502, in _create_connection
raise SMTPConnectTimeoutError(
aiosmtplib.errors.SMTPConnectTimeoutError: Timed out connecting to smtp.gmail.com on port 587
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
return await self.app(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/fastapi/applications.py", line 1054, in __call__
await super().__call__(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/applications.py", line 113, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/middleware/errors.py", line 187, in __call__
raise exc
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/middleware/errors.py", line 165, in __call__
await self.app(scope, receive, _send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/middleware/cors.py", line 93, in __call__
await self.simple_response(scope, receive, send, request_headers=headers)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/middleware/cors.py", line 144, in simple_response
await self.app(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/middleware/exceptions.py", line 62, in __call__
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app
raise exc
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app
await app(scope, receive, sender)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/routing.py", line 715, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/routing.py", line 735, in app
await route.handle(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/routing.py", line 288, in handle
await self.app(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/routing.py", line 76, in app
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/_exception_handler.py", line 62, in wrapped_app
raise exc
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/_exception_handler.py", line 51, in wrapped_app
await app(scope, receive, sender)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/starlette/routing.py", line 73, in app
response = await f(request)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/fastapi/routing.py", line 301, in app
raw_response = await run_endpoint_function(
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/fastapi/routing.py", line 212, in run_endpoint_function
return await dependant.call(**values)
File "/Users/i-hmohas/Desktop/Backend/aie-portal-model-catalog-backend/app/routes/model_flow_steps/model_flow_notification_and_status.py", line 93, in simple_send
await fm.send_message(message)
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/fastapi_mail/fastmail.py", line 109, in send_message
async with Connection(self.config) as session:
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/fastapi_mail/connection.py", line 23, in __aenter__
await self._configure_connection()
File "/Users/i-hmohas/Library/Python/3.9/lib/python/site-packages/fastapi_mail/connection.py", line 53, in _configure_connection
raise ConnectionErrors(
fastapi_mail.errors.ConnectionErrors: Exception raised Timed out connecting to smtp.gmail.com on port 587, check your credentials or email service configuration
This used to work a few days ago with the exact same setup and sent email from backend. I don’t know what happened that it does not work anymore.I tried this but doesn’t work.
P.S: The only difference might be I am now in the office but it used to work from home with VPN so should not really matter.