email_utils.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os
  2. from email.message import EmailMessage
  3. from smtplib import SMTP
  4. from jinja2 import Environment, FileSystemLoader
  5. from app.config import SUPPORT_EMAIL, ROOT_DIR
  6. def _render(template_name, **kwargs) -> str:
  7. templates_dir = os.path.join(ROOT_DIR, "templates", "emails")
  8. env = Environment(loader=FileSystemLoader(templates_dir))
  9. template = env.get_template(template_name)
  10. return template.render(**kwargs)
  11. def send_welcome_email(email, name):
  12. send_by_postfix(
  13. email,
  14. f"{name}, welcome to SimpleLogin!",
  15. _render("welcome.txt", name=name),
  16. _render("welcome.html", name=name),
  17. )
  18. def send_activation_email(email, name, activation_link):
  19. send_by_postfix(
  20. email,
  21. f"{name}, just one more step to join SimpleLogin",
  22. _render("activation.txt", name=name, activation_link=activation_link),
  23. _render("activation.html", name=name, activation_link=activation_link),
  24. )
  25. def send_reset_password_email(email, name, reset_password_link):
  26. send_by_postfix(
  27. email,
  28. f"{name}, reset your password on SimpleLogin",
  29. _render(
  30. "reset-password.txt", name=name, reset_password_link=reset_password_link
  31. ),
  32. _render(
  33. "reset-password.html", name=name, reset_password_link=reset_password_link
  34. ),
  35. )
  36. def send_new_app_email(email, name):
  37. send_by_postfix(
  38. email,
  39. f"{name}, any questions/feedbacks for SimpleLogin?",
  40. _render("new-app.txt", name=name),
  41. _render("new-app.html", name=name),
  42. )
  43. def send_by_postfix(to_email, subject, plaintext, html):
  44. # host IP, setup via Docker network
  45. smtp = SMTP("1.1.1.1", 25)
  46. msg = EmailMessage()
  47. msg["Subject"] = subject
  48. msg["From"] = f"Son from SimpleLogin <{SUPPORT_EMAIL}>"
  49. msg["To"] = to_email
  50. msg.set_content(plaintext)
  51. if html is not None:
  52. msg.add_alternative(html, subtype="html")
  53. smtp.send_message(msg, from_addr=SUPPORT_EMAIL, to_addrs=[to_email])
  54. def notify_admin(subject, html_content=""):
  55. send_by_postfix(SUPPORT_EMAIL, subject, html_content, html_content)