email.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import os
  2. from pathlib import Path
  3. from typing import NoReturn
  4. from fastapi import BackgroundTasks
  5. from fastapi_mail import ConnectionConfig, FastMail, MessageSchema, MessageType
  6. from jinja2 import Environment, FileSystemLoader
  7. from app.parser import read_file
  8. def prepare_email(
  9. git_repo: str, document_match: list[str], block_types: list[str], order
  10. ) -> dict[str]:
  11. """Prepare email message."""
  12. filename = "checkout/email"
  13. doc = read_file(
  14. git_repo,
  15. filename,
  16. document_match,
  17. block_types,
  18. "",
  19. )
  20. # -- setup jinja template and expand data in it
  21. environment = Environment(loader=FileSystemLoader(f"{Path(git_repo) / 'checkout'}"))
  22. template = environment.get_template("email.md")
  23. body = template.render(order)
  24. # clean up data
  25. block_marker = "\n---\n"
  26. blocks = body.split(block_marker)
  27. blocks = [block.strip() for block in blocks]
  28. email_body = "\n\n---\n\n".join(blocks[1:])
  29. return {
  30. "sender": doc.meta.sender,
  31. "subject": doc.meta.title,
  32. "body": email_body,
  33. }
  34. async def send_email(
  35. settings: dict[str, list[str]],
  36. order: dict[str],
  37. background_tasks: BackgroundTasks | None = None,
  38. ) -> NoReturn | tuple[FastMail, MessageSchema]:
  39. """Send email to given customer. Async process."""
  40. email_data = prepare_email(
  41. settings["git_repo"], settings["document_match"], settings["block_types"], order
  42. )
  43. conf = ConnectionConfig(
  44. MAIL_USERNAME=os.getenv("MAIL_USERNAME"),
  45. MAIL_PASSWORD=os.getenv("MAIL_PASSWORD"),
  46. MAIL_FROM=os.getenv("MAIL_FROM"),
  47. MAIL_FROM_NAME=email_data["sender"],
  48. MAIL_PORT=os.getenv("MAIL_PORT"),
  49. MAIL_SERVER=os.getenv("MAIL_SERVER"),
  50. MAIL_STARTTLS=os.getenv("MAIL_STARTTLS"),
  51. MAIL_SSL_TLS=os.getenv("MAIL_SSL_TLS"),
  52. USE_CREDENTIALS=os.getenv("MAIL_USE_CREDENTIALS"),
  53. VALIDATE_CERTS=os.getenv("MAIL_VALIDATE_CERTS"),
  54. )
  55. recipients = []
  56. if background_tasks:
  57. recipients.append(order['email'])
  58. else:
  59. recipients.append(os.getenv("MAIL_TO_TEST"))
  60. message = MessageSchema(
  61. subject=email_data["subject"],
  62. recipients=recipients,
  63. body=email_data["body"],
  64. subtype=MessageType.plain,
  65. bcc=[os.getenv("MAIL_FROM")]
  66. )
  67. fm = FastMail(conf)
  68. if background_tasks:
  69. background_tasks.add_task(fm.send_message, message)
  70. else:
  71. return (fm, message)