body.py 9.2 KB

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