body.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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
  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. extra = {} if extra is None else extra
  49. df = pd.DataFrame(tbl)
  50. tbl_html = self.table_template.render({"df": df, **extra})
  51. return Markup(tbl_html)
  52. def render(self, cont:str, tables=None, jinja_params=None):
  53. tables = {} if tables is None else tables
  54. jinja_params = {} if jinja_params is None else jinja_params
  55. tables = {
  56. name: self.render_table(tbl)
  57. for name, tbl in tables.items()
  58. }
  59. return self.render_body(cont, jinja_params={**tables, **jinja_params})
  60. class TextBody(Body):
  61. def attach(self, msg:EmailMessage, text:str, **kwargs):
  62. if self.use_jinja:
  63. text = self.render(text, **kwargs)
  64. msg.set_content(text)
  65. class HTMLBody(Body):
  66. def __init__(self, domain:str=None, **kwargs):
  67. super().__init__(**kwargs)
  68. self.domain = domain
  69. def attach(self,
  70. msg:EmailMessage,
  71. html:str,
  72. images: Dict[str, Union[Path, str, bytes]]=None,
  73. **kwargs):
  74. """Render email HTML
  75. Parameters
  76. ----------
  77. msg : EmailMessage
  78. Message of the email.
  79. html : str
  80. HTML that may contain Jinja syntax.
  81. body_images : dict of path-likes, bytes
  82. Images to embed to the HTML. The dict keys correspond to variables in the html.
  83. body_tables : dict of pd.DataFrame
  84. Tables to embed to the HTML
  85. jinja_params : dict
  86. Extra Jinja parameters for the HTML.
  87. """
  88. if self.use_jinja:
  89. domain = parseaddr(msg["from"])[1].split("@")[-1] if self.domain is None else self.domain
  90. html, cids = self.render(
  91. html,
  92. images=images,
  93. domain=domain,
  94. **kwargs
  95. )
  96. msg.add_alternative(html, subtype='html')
  97. if self.use_jinja and images is not None:
  98. # https://stackoverflow.com/a/49098251/13696660
  99. html_msg = msg.get_payload()[-1]
  100. cid_path_mapping = {cids[name]: path for name, path in images.items()}
  101. self.attach_imgs(html_msg, cid_path_mapping)
  102. def render(self, html:str, images:Dict[str, Union[dict, bytes, Path]]=None, tables:Dict[str, 'DataFrame']=None, jinja_params:dict=None, domain=None):
  103. """Render Email HTML body (sets cid for image sources and adds data as other parameters)
  104. Parameters
  105. ----------
  106. html : str
  107. HTML (template) to be rendered with images,
  108. tables etc. May contain...
  109. images : list-like, optional
  110. A list-like of images to be rendered to the HTML.
  111. Values represent the Jinja variables found in the html
  112. and the images are rendered on those positions.
  113. tables : dict, optional
  114. A dict of tables to render to the HTML. The keys
  115. should represent variables in ``html`` and values
  116. should be Pandas dataframes to be rendered to the HTML.
  117. extra : dict, optional
  118. Extra items to be passed to the HTML Jinja template.
  119. table_theme : str, optional
  120. Theme to use for generating the HTML version of the
  121. table dataframes. See included files in the
  122. environment pybox.jinja2.envs.inline. The themes
  123. are stems of the files in templates/inline/table.
  124. Returns
  125. -------
  126. str, dict
  127. Rendered HTML and Content-IDs to the images.
  128. """
  129. images = {} if images is None else images
  130. # Define CIDs for images
  131. cids = {
  132. name: make_msgid(domain=domain)
  133. for name in images
  134. }
  135. html_images = {
  136. name: BodyImage(cid=cid[1:-1], name=name, obj=images[name]) # taking "<" and ">" from beginning and end
  137. for name, cid in cids.items()
  138. }
  139. # Tables to HTML
  140. jinja_params = {**jinja_params, **html_images}
  141. html = super().render(html, tables=tables, jinja_params=jinja_params)
  142. return html, cids
  143. def attach_imgs(self, msg_body:EmailMessage, imgs:Dict[str, Union[ByteString, str, Dict[str, Union[ByteString, str]]]]):
  144. """Attach CID images to Message Body
  145. Examples:
  146. ---------
  147. attach_imgs(..., {"<>"})
  148. """
  149. for cid, img in imgs.items():
  150. if is_bytes(img) or isinstance(img, BytesIO):
  151. # We just assume the user meant PNG. If not, it should have been specified
  152. img_content = img.read() if hasattr(img, "read") else img
  153. kwds = {
  154. 'maintype': 'image',
  155. 'subtype': 'png',
  156. }
  157. elif isinstance(img, dict):
  158. # Expecting dict explanation of bytes
  159. # ie. {"maintype": "image", "subtype": "png", "content": b'...'}
  160. # Setting defaults
  161. img['maintype'] = img.get('maintype', 'image')
  162. # Validation
  163. required_keys = ("content", "subtype")
  164. if any(key not in img for key in required_keys):
  165. missing_keys = tuple(key for key in required_keys if key not in img)
  166. raise KeyError(f"Dict representation of an image missing keys: {missing_keys}")
  167. img_content = img.pop("content")
  168. kwds = img
  169. elif isinstance(img, Path) or (isinstance(img, str) and Path(img).is_file()):
  170. path = img
  171. maintype, subtype = mimetypes.guess_type(str(path))[0].split('/')
  172. with open(path, "rb") as img:
  173. img_content = img.read()
  174. kwds = {
  175. 'maintype': maintype,
  176. 'subtype': subtype,
  177. }
  178. elif plt is not None and isinstance(img, plt.Figure):
  179. buf = BytesIO()
  180. img.savefig(buf, format='png')
  181. buf.seek(0)
  182. img_content = buf.read()
  183. kwds = {
  184. 'maintype': 'image',
  185. 'subtype': 'png',
  186. }
  187. elif PIL is not None and isinstance(img, PIL.Image.Image):
  188. buf = BytesIO()
  189. img.save(buf, format='PNG')
  190. buf.seek(0)
  191. img_content = buf.read()
  192. kwds = {
  193. 'maintype': 'image',
  194. 'subtype': 'png',
  195. }
  196. else:
  197. # Cannot be figured out
  198. if isinstance(img, str):
  199. raise ValueError(f"Unknown image string '{img}'. Maybe incorrect path?")
  200. raise TypeError(f"Unknown image {repr(img)}")
  201. msg_body.add_related(
  202. img_content,
  203. cid=cid,
  204. **kwds
  205. )