body.py 8.7 KB

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