|
| 1 | +from app.config import email_conf |
| 2 | +from app.database.models import Event, User |
| 3 | +from fastapi import BackgroundTasks |
| 4 | +from fastapi_mail import FastMail, MessageSchema |
| 5 | +from sqlalchemy.orm.session import Session |
| 6 | + |
| 7 | +mail = FastMail(email_conf) |
| 8 | + |
| 9 | + |
| 10 | +def send( |
| 11 | + session: Session, event_used: int, user_to_send: int, |
| 12 | + title: str, background_tasks: BackgroundTasks = BackgroundTasks |
| 13 | +) -> bool: |
| 14 | + """This function is being used to send emails in the background. |
| 15 | + It takes an event and a user and it sends the event to the user. |
| 16 | +
|
| 17 | + Args: |
| 18 | + session(Session): The session to redirect to the database. |
| 19 | + title (str): Title of the email that is being sent. |
| 20 | + event_used (int): Id number of the event that is used. |
| 21 | + user_to_send (int): Id number of user that we want to notify. |
| 22 | + background_tasks (BackgroundTasks): Function from fastapi that lets |
| 23 | + you apply tasks in the background. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + bool: Returns True if the email was sent, else returns False. |
| 27 | + """ |
| 28 | + event_used = session.query(Event).filter( |
| 29 | + Event.id == event_used).first() |
| 30 | + user_to_send = session.query(User).filter( |
| 31 | + User.id == user_to_send).first() |
| 32 | + if not user_to_send or not event_used: |
| 33 | + return False |
| 34 | + message = MessageSchema( |
| 35 | + subject=f"{title} {event_used.title}", |
| 36 | + recipients={"email": [user_to_send.email]}.get("email"), |
| 37 | + body=f"begins at:{event_used.start} : {event_used.content}", |
| 38 | + ) |
| 39 | + background_tasks.add_task(mail.send_message, message) |
| 40 | + return True |
0 commit comments