nopaque/app/email.py

33 lines
781 B
Python
Raw Normal View History

2024-11-05 08:05:31 +00:00
from flask import current_app, Flask, render_template
2019-07-08 09:29:11 +00:00
from flask_mail import Message
from threading import Thread
from app import mail
2019-07-08 09:29:11 +00:00
2024-11-05 08:05:31 +00:00
def create_message(
recipient: str,
subject: str,
template: str,
**context
) -> Message:
message = Message(
body=render_template(f'{template}.txt.j2', **context),
html=render_template(f'{template}.html.j2', **context),
recipients=[recipient],
2024-11-05 08:05:31 +00:00
subject=f'[nopaque] {subject}'
)
2024-11-05 08:05:31 +00:00
return message
2020-04-21 08:26:44 +00:00
2024-11-05 08:05:31 +00:00
def send(message: Message) -> Thread:
def _send(app: Flask, message: Message):
with app.app_context():
2024-11-05 08:05:31 +00:00
mail.send(message)
2024-11-05 08:05:31 +00:00
thread = Thread(
target=_send,
args=[current_app._get_current_object(), message]
)
thread.start()
return thread