body.py 8.5 KB

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