wstkeys/services/mailer.py

55 lines
1.5 KiB
Python

import os
import smtplib
from email.message import EmailMessage
from dotenv import load_dotenv
from utils import build_items_html, build_keys_html, render_template
load_dotenv()
EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS")
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")
def send_plain_email(to_address: str, subject: str, body: str):
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = EMAIL_ADDRESS
msg['To'] = to_address
msg.set_content(body)
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls()
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
print(f"Plain email sent to {to_address}")
def send_html_email(to_address: str, data: dict):
msg = EmailMessage()
msg['Subject'] = f"Order #{data['order_id']}"
msg['From'] = EMAIL_ADDRESS
msg['To'] = to_address
with open('templates/welcome.html', 'r', encoding='utf-8') as f:
html_template = f.read()
html_template = html_template.replace(
"{{items}}", build_items_html(data["items"])
)
html_template = html_template.replace(
"{{keys_block}}", build_keys_html(data.get("keys"))
)
html_content = render_template(html_template, data)
msg.add_alternative(html_content, subtype='html')
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls()
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
print(f"HTML email sent to {to_address}")