61 lines
2.1 KiB
Python
61 lines
2.1 KiB
Python
import smtplib
|
|
from email.mime.multipart import MIMEMultipart
|
|
from email.mime.text import MIMEText
|
|
from email.mime.image import MIMEImage
|
|
from email.utils import formataddr
|
|
from pathlib import Path
|
|
from flask import current_app, render_template
|
|
|
|
|
|
def send_invitation(guest, event_name="Корпоратив", additional_text=""):
|
|
"""Отправляет приглашение гостю на email с QR-кодом во вложении."""
|
|
config = current_app.config
|
|
|
|
msg = MIMEMultipart("related")
|
|
msg["Subject"] = f"Приглашение на мероприятие: {event_name}"
|
|
msg["From"] = formataddr(("InviteMe", config.get("MAIL_DEFAULT_SENDER", config["MAIL_USERNAME"])))
|
|
msg["To"] = guest.email
|
|
|
|
# HTML-шаблон письма
|
|
html_body = render_template(
|
|
"email/invitation.html",
|
|
guest=guest,
|
|
event_name=event_name,
|
|
additional_text=additional_text,
|
|
qr_cid="qr_code_image",
|
|
)
|
|
|
|
msg.attach(MIMEText(html_body, "html", "utf-8"))
|
|
|
|
# Прикрепляем QR-код
|
|
qr_path = Path(config["QR_FOLDER"]) / guest.qr_filename
|
|
if qr_path.exists():
|
|
with open(qr_path, "rb") as img_file:
|
|
img = MIMEImage(img_file.read())
|
|
img.add_header("Content-ID", "<qr_code_image>")
|
|
img.add_header("Content-Disposition", "inline", filename=guest.qr_filename)
|
|
msg.attach(img)
|
|
|
|
# Отправка через SMTP
|
|
server = config["MAIL_SERVER"]
|
|
port = config["MAIL_PORT"]
|
|
username = config["MAIL_USERNAME"]
|
|
password = config["MAIL_PASSWORD"]
|
|
use_ssl = config.get("MAIL_USE_SSL", True)
|
|
|
|
if not username or not password:
|
|
raise ValueError("MAIL_USERNAME и MAIL_PASSWORD должны быть указаны в конфигурации")
|
|
|
|
if use_ssl:
|
|
with smtplib.SMTP_SSL(server, port) as smtp:
|
|
smtp.login(username, password)
|
|
smtp.send_message(msg)
|
|
else:
|
|
with smtplib.SMTP(server, port) as smtp:
|
|
smtp.starttls()
|
|
smtp.login(username, password)
|
|
smtp.send_message(msg)
|
|
|
|
guest.invitation_sent = True
|
|
return True
|