templating.rst 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. .. meta::
  2. :description: Send templated email in Python using Jinja.
  3. :keywords: send, email, Python, jinja, environment
  4. .. _templating:
  5. Jinja Environments
  6. ==================
  7. There are two ways of setting a custom Jinja env
  8. to Red Mail: from paths or directly setting the
  9. envs.
  10. To set the paths and let Red Mail to create the
  11. environments:
  12. .. code-block:: python
  13. from redmail import EmailSender
  14. email = EmailSender(host="localhost", port=0)
  15. email.set_template_paths(
  16. html="path/html/templates",
  17. text="path/text/templates",
  18. )
  19. To set the Jinja environments:
  20. .. code-block:: python
  21. import jinja2
  22. # Create an env
  23. jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader("path/to/templates"))
  24. email_sender.templates_html = jinja_env
  25. email_sender.templates_text = jinja_env
  26. .. note::
  27. If you are dissatisfied with default HTML and text
  28. table templates, you can also pass ``html_table``
  29. and ``text_table`` to specify the templates used
  30. to render embedded tables:
  31. .. code-block:: python
  32. email.set_template_paths(
  33. html_table="path/html/tables",
  34. text_table="path/text/tables",
  35. )
  36. The environments are in the attributes ``templates_html_table``
  37. and ``templates_text_table`` respectively.
  38. Next we will make a simple template, let's call it
  39. ``event_card.html``:
  40. .. code-block:: html
  41. <h1>Hi {{ participant }}!</h1>
  42. <p>
  43. Thank you for being a valuable member of our
  44. community! We are organizing an event
  45. {{ event_name }} and we would like to invite
  46. you.
  47. </p>
  48. <p>Kind regards,<br>
  49. <em>{{ organizer }} </em>
  50. </p>
  51. Then we can use this template:
  52. .. code-block:: python
  53. email.send(
  54. subject='email subject',
  55. receivers=['first.last@example.com'],
  56. html_template='event_card.html',
  57. body_params={
  58. 'participant': 'Jack',
  59. 'event_name': 'Open data',
  60. 'organizer': 'Organization.org'
  61. }
  62. )