body.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. from email.message import EmailMessage
  2. import mimetypes
  3. from io import BytesIO
  4. from pathlib import Path
  5. from typing import Dict, Union, ByteString
  6. from pathlib import Path
  7. from redmail.utils import is_bytes
  8. from redmail.utils import import_from_string
  9. from email.utils import make_msgid
  10. from jinja2.environment import Template, Environment
  11. import pandas as pd
  12. from markupsafe import Markup
  13. # We try to import matplotlib and PIL but if fails, they will be None
  14. from .utils import PIL, plt
  15. class BodyImage:
  16. "Utility class to represent image on HTML"
  17. def __init__(self, cid, obj, name=None):
  18. self.cid = cid
  19. self.obj = obj
  20. self.name = name
  21. def __str__(self):
  22. return f'<img src="{self.src}">'
  23. @property
  24. def src(self):
  25. return f'cid:{ self.cid }'
  26. class Body:
  27. def __init__(self, template:Template=None, table_template:Template=None):
  28. self.template = template
  29. self.table_template = table_template
  30. def render_body(self, body:str, jinja_params:dict):
  31. if body is not None and self.template is not None:
  32. raise ValueError("Either body or template must be specified but not both.")
  33. if body is not None:
  34. template = Environment().from_string(body)
  35. else:
  36. template = self.template
  37. return template.render(**jinja_params)
  38. def render_table(self, tbl, extra=None):
  39. # TODO: Nicer tables.
  40. # https://stackoverflow.com/a/55356741/13696660
  41. # Email HTML (generally) does not support CSS
  42. extra = {} if extra is None else extra
  43. df = pd.DataFrame(tbl)
  44. tbl_html = self.table_template.render({"df": df, **extra})
  45. return Markup(tbl_html)
  46. def render(self, cont:str, tables=None, jinja_params=None):
  47. tables = {} if tables is None else tables
  48. jinja_params = {} if jinja_params is None else jinja_params
  49. tables = {
  50. name: self.render_table(tbl)
  51. for name, tbl in tables.items()
  52. }
  53. return self.render_body(cont, jinja_params={**tables, **jinja_params})
  54. class TextBody(Body):
  55. def attach(self, msg:EmailMessage, text:str, **kwargs):
  56. text = self.render(text, **kwargs)
  57. msg.set_content(text)
  58. class HTMLBody(Body):
  59. def __init__(self, domain:str=None, **kwargs):
  60. super().__init__(**kwargs)
  61. self.domain = domain
  62. def attach(self,
  63. msg:EmailMessage,
  64. html:str,
  65. images: Dict[str, Union[Path, str, bytes]]=None,
  66. **kwargs):
  67. """Render email HTML
  68. Parameters
  69. ----------
  70. msg : EmailMessage
  71. Message of the email.
  72. html : str
  73. HTML that may contain Jinja syntax.
  74. body_images : dict of path-likes, bytes
  75. Images to embed to the HTML. The dict keys correspond to variables in the html.
  76. body_tables : dict of pd.DataFrame
  77. Tables to embed to the HTML
  78. jinja_params : dict
  79. Extra Jinja parameters for the HTML.
  80. """
  81. domain = msg["from"].split("@")[-1] if self.domain is None else self.domain
  82. html, cids = self.render(
  83. html,
  84. images=images,
  85. domain=domain,
  86. **kwargs
  87. )
  88. msg.add_alternative(html, subtype='html')
  89. if images is not None:
  90. # https://stackoverflow.com/a/49098251/13696660
  91. html_msg = msg.get_payload()[-1]
  92. cid_path_mapping = {cids[name]: path for name, path in images.items()}
  93. self.attach_imgs(html_msg, cid_path_mapping)
  94. def render(self, html:str, images:Dict[str, Union[dict, bytes, Path]]=None, tables:Dict[str, pd.DataFrame]=None, jinja_params:dict=None, domain=None):
  95. """Render Email HTML body (sets cid for image sources and adds data as other parameters)
  96. Parameters
  97. ----------
  98. html : str
  99. HTML (template) to be rendered with images,
  100. tables etc. May contain...
  101. images : list-like, optional
  102. A list-like of images to be rendered to the HTML.
  103. Values represent the Jinja variables found in the html
  104. and the images are rendered on those positions.
  105. tables : dict, optional
  106. A dict of tables to render to the HTML. The keys
  107. should represent variables in ``html`` and values
  108. should be Pandas dataframes to be rendered to the HTML.
  109. extra : dict, optional
  110. Extra items to be passed to the HTML Jinja template.
  111. table_theme : str, optional
  112. Theme to use for generating the HTML version of the
  113. table dataframes. See included files in the
  114. environment pybox.jinja2.envs.inline. The themes
  115. are stems of the files in templates/inline/table.
  116. Returns
  117. -------
  118. str, dict
  119. Rendered HTML and Content-IDs to the images.
  120. """
  121. images = {} if images is None else images
  122. # Define CIDs for images
  123. cids = {
  124. name: make_msgid(domain=domain)
  125. for name in images
  126. }
  127. html_images = {
  128. name: BodyImage(cid=cid[1:-1], name=name, obj=images[name]) # taking "<" and ">" from beginning and end
  129. for name, cid in cids.items()
  130. }
  131. # Tables to HTML
  132. jinja_params = {**jinja_params, **html_images}
  133. html = super().render(html, tables=tables, jinja_params=jinja_params)
  134. return html, cids
  135. def attach_imgs(self, msg_body:EmailMessage, imgs:Dict[str, Union[ByteString, str, Dict[str, Union[ByteString, str]]]]):
  136. """Attach CID images to Message Body
  137. Examples:
  138. ---------
  139. attach_imgs(..., {"<>"})
  140. """
  141. for cid, img in imgs.items():
  142. if is_bytes(img) or isinstance(img, BytesIO):
  143. # We just assume the user meant PNG. If not, it should have been specified
  144. img_content = img.read() if hasattr(img, "read") else img
  145. maintype = "image"
  146. subtype = "png"
  147. elif isinstance(img, dict):
  148. # Expecting dict explanation of bytes
  149. # ie. {"maintype": "image", "subtype": "png", "content"}
  150. required_keys = ("content", "maintype", "subtype")
  151. if any(key not in img for key in required_keys):
  152. missing_keys = tuple(key for key in required_keys if key not in img)
  153. raise KeyError(f"Image {img:!r} missing keys: {missing_keys:!r}")
  154. img_content = img["content"]
  155. maintype = "image"
  156. subtype = "png"
  157. elif isinstance(img, Path) or (isinstance(img, str) and Path(img).is_file()):
  158. path = img
  159. maintype, subtype = mimetypes.guess_type(str(path))[0].split('/')
  160. with open(path, "rb") as img:
  161. img_content = img.read()
  162. elif plt is not None and isinstance(img, plt.Figure):
  163. buf = BytesIO()
  164. img.savefig(buf, format='png')
  165. buf.seek(0)
  166. img_content = buf.read()
  167. maintype = "image"
  168. subtype = "png"
  169. elif PIL is not None and isinstance(img, PIL.Image.Image):
  170. buf = BytesIO()
  171. img.save(buf, format='PNG')
  172. buf.seek(0)
  173. img_content = buf.read()
  174. maintype = "image"
  175. subtype = "png"
  176. else:
  177. # Cannot be figured out
  178. if isinstance(img, str):
  179. raise ValueError(f"Unknown image string '{img}'. Maybe incorrect path?")
  180. raise TypeError(f"Unknown image {repr(img)}")
  181. msg_body.add_related(
  182. img_content,
  183. maintype=maintype,
  184. subtype=subtype,
  185. cid=cid
  186. )