Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

mail_inner_task.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import logging
  2. import time
  3. from collections.abc import Mapping
  4. from typing import Any
  5. import click
  6. from celery import shared_task
  7. from flask import render_template_string
  8. from jinja2.runtime import Context
  9. from jinja2.sandbox import ImmutableSandboxedEnvironment
  10. from configs import dify_config
  11. from configs.feature import TemplateMode
  12. from extensions.ext_mail import mail
  13. from libs.email_i18n import get_email_i18n_service
  14. logger = logging.getLogger(__name__)
  15. class SandboxedEnvironment(ImmutableSandboxedEnvironment):
  16. def __init__(self, timeout: int, *args: Any, **kwargs: Any):
  17. self._timeout_time = time.time() + timeout
  18. super().__init__(*args, **kwargs)
  19. def call(self, context: Context, obj: Any, *args: Any, **kwargs: Any) -> Any:
  20. if time.time() > self._timeout_time:
  21. raise TimeoutError("Template rendering timeout")
  22. return super().call(context, obj, *args, **kwargs)
  23. def _render_template_with_strategy(body: str, substitutions: Mapping[str, str]) -> str:
  24. mode = dify_config.MAIL_TEMPLATING_MODE
  25. timeout = dify_config.MAIL_TEMPLATING_TIMEOUT
  26. if mode == TemplateMode.UNSAFE:
  27. return render_template_string(body, **substitutions)
  28. if mode == TemplateMode.SANDBOX:
  29. tmpl = SandboxedEnvironment(timeout=timeout).from_string(body)
  30. return tmpl.render(substitutions)
  31. if mode == TemplateMode.DISABLED:
  32. return body
  33. raise ValueError(f"Unsupported mail templating mode: {mode}")
  34. @shared_task(queue="mail")
  35. def send_inner_email_task(to: list[str], subject: str, body: str, substitutions: Mapping[str, str]):
  36. if not mail.is_inited():
  37. return
  38. logger.info(click.style(f"Start enterprise mail to {to} with subject {subject}", fg="green"))
  39. start_at = time.perf_counter()
  40. try:
  41. html_content = _render_template_with_strategy(body, substitutions)
  42. email_service = get_email_i18n_service()
  43. email_service.send_raw_email(to=to, subject=subject, html_content=html_content)
  44. end_at = time.perf_counter()
  45. logger.info(click.style(f"Send enterprise mail to {to} succeeded: latency: {end_at - start_at}", fg="green"))
  46. except Exception:
  47. logger.exception("Send enterprise mail to %s failed", to)