add user email

This commit is contained in:
Valentin CZERYBA 2023-10-15 14:12:12 +02:00
parent b81119f53e
commit 228c9bebb8
3 changed files with 27 additions and 6 deletions

View File

@ -3,11 +3,11 @@ from pathlib import Path
import os
conf = ConnectionConfig(
MAIL_USERNAME = "YourUsername",
MAIL_PASSWORD = "strong_password",
MAIL_FROM = "your@email.com",
MAIL_PORT = 587,
MAIL_SERVER = "your mail server",
MAIL_USERNAME = os.environ["MAILER_USERNAME"],
MAIL_PASSWORD = os.environ["MAILER_PASSWORD"],
MAIL_FROM = os.environ["MAILER_FROM"],
MAIL_PORT = os.environ["MAILER_PORT"],
MAIL_SERVER = os.environ["MAILER_HOST"],
MAIL_STARTTLS = True,
MAIL_SSL_TLS = False,
TEMPLATE_FOLDER = Path(__file__).parents[1] / 'templates',

View File

@ -4,6 +4,7 @@ from ..models import users
from typing import Annotated
from bson import ObjectId
from fastapi.responses import JSONResponse
from fastapi_mail import MessageSchema, MessageType
router = APIRouter()
@ -114,8 +115,22 @@ async def read_users_me(userSingle: users.UserCreate | None = None):
status_code=status.HTTP_400_BAD_REQUEST,
detail="Body request is empty"
)
fm = FastMail(mail.conf)
user_repository = users.UserRepository(database=database.database)
user = user_repository.find_one_by({"username": {'$eq': userSingle.username}})
if user is not None:
raise HTTPException(
status_code=status.HTTP_204_NO_CONTENT,
detail="User is already exist"
)
fm = FastMail(mail.conf)
message = MessageSchema(
subject="Fastapi-Mail module",
recipients=userSingle.email,
template_body=email.dict(),
subtype=MessageType.html,
)
await fm.send_message(message, template_name="mailer.html")
current_user = users.User(username=userSingle.username, password=user_token.get_password_hash(userSingle.password), email=userSingle.email)
user_repository.save(current_user)
return JSONResponse(status_code=200, content={"message": "email has been sent"})

View File

@ -0,0 +1,6 @@
<html>
<head><title>Email</title></head>
<body><p>Voici un lien https://localhost:8080/api/mail?key={key}&username={username}
</p></body>
</html>