56 lines
No EOL
1.6 KiB
Python
56 lines
No EOL
1.6 KiB
Python
"""
|
|
Email utilities for the NetViz application.
|
|
"""
|
|
from flask import current_app, render_template
|
|
from flask_mail import Message
|
|
from threading import Thread
|
|
|
|
from app.extensions import mail
|
|
from app.models.user import User
|
|
|
|
|
|
def send_async_email(app, msg):
|
|
"""Send email asynchronously."""
|
|
with app.app_context():
|
|
mail.send(msg)
|
|
|
|
|
|
def send_email(subject, sender, recipients, text_body, html_body):
|
|
"""
|
|
Send an email.
|
|
|
|
Args:
|
|
subject: Email subject
|
|
sender: Sender email address
|
|
recipients: List of recipient email addresses
|
|
text_body: Plain text email body
|
|
html_body: HTML email body
|
|
"""
|
|
msg = Message(subject, sender=sender, recipients=recipients)
|
|
msg.body = text_body
|
|
msg.html = html_body
|
|
|
|
# Send email asynchronously to not block the request
|
|
Thread(
|
|
target=send_async_email,
|
|
args=(current_app._get_current_object(), msg)
|
|
).start()
|
|
|
|
|
|
def send_password_reset_email(user: User):
|
|
"""
|
|
Send a password reset email to a user.
|
|
|
|
Args:
|
|
user: The user requesting password reset
|
|
"""
|
|
token = user.generate_reset_token()
|
|
reset_url = f"{current_app.config['SERVER_NAME']}/auth/reset-password/{token}"
|
|
|
|
send_email(
|
|
subject="[NetViz] Reset Your Password",
|
|
sender=current_app.config['MAIL_DEFAULT_SENDER'],
|
|
recipients=[user.email],
|
|
text_body=render_template("email/reset_password.txt", user=user, reset_url=reset_url),
|
|
html_body=render_template("email/reset_password.html", user=user, reset_url=reset_url)
|
|
) |