sender.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. from email.message import EmailMessage
  2. from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
  3. import jinja2
  4. from redmail.email.attachment import Attachments
  5. from redmail.email.body import HTMLBody, TextBody
  6. from redmail.models import EmailAddress, Error
  7. from .envs import get_span, is_last_group_row
  8. import smtplib
  9. from pathlib import Path
  10. from platform import node
  11. from getpass import getuser
  12. import datetime
  13. import os
  14. if TYPE_CHECKING:
  15. # These are never imported but just for linters
  16. import pandas as pd
  17. from PIL.Image import Image
  18. import matplotlib.pyplot as plt
  19. class EmailSender:
  20. """Red Mail Email Sender
  21. Parameters
  22. ----------
  23. host : str
  24. SMTP host address.
  25. port : int
  26. Port to the SMTP server.
  27. user_name : str, optional
  28. User name to authenticate on the server.
  29. password : str, optional
  30. User password to authenticate on the server.
  31. Examples
  32. --------
  33. .. code-block:: python
  34. email = EmailSender(server="smtp.mymail.com", port=123)
  35. email.send(
  36. subject="Example Email",
  37. sender="me@example.com",
  38. receivers=["you@example.com"],
  39. )
  40. """
  41. default_html_theme = "modest.html"
  42. default_text_theme = "pandas.txt"
  43. templates_html = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates/html")))
  44. templates_html_table = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates/html/table")))
  45. templates_text = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates/text")))
  46. templates_text_table = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates/text/table")))
  47. # Set globals
  48. templates_html_table.globals["get_span"] = get_span
  49. templates_text_table.globals["get_span"] = get_span
  50. templates_html_table.globals["is_last_group_row"] = is_last_group_row
  51. templates_text_table.globals["is_last_group_row"] = is_last_group_row
  52. attachment_encoding = 'UTF-8'
  53. _cls_smtp_server = smtplib.SMTP
  54. def __init__(self, host:str, port:int, user_name:str=None, password:str=None):
  55. self.host = host
  56. self.port = port
  57. self.user_name = user_name
  58. self.password = password
  59. # Defaults
  60. self.sender = None
  61. self.receivers = None
  62. self.cc = None
  63. self.bcc = None
  64. self.subject = None
  65. self.text = None
  66. self.html = None
  67. self.html_template = None
  68. self.text_template = None
  69. def send(self,
  70. subject:Optional[str]=None,
  71. sender:Optional[str]=None,
  72. receivers:Union[List[str], str, None]=None,
  73. cc:Union[List[str], str, None]=None,
  74. bcc:Union[List[str], str, None]=None,
  75. html:Optional[str]=None,
  76. text:Optional[str]=None,
  77. html_template:Optional[str]=None,
  78. text_template:Optional[str]=None,
  79. body_images:Optional[Dict[str, Union[str, bytes, 'plt.Figure', 'Image']]]=None,
  80. body_tables:Optional[Dict[str, 'pd.DataFrame']]=None,
  81. body_params:Optional[Dict[str, Any]]=None,
  82. attachments:Optional[Dict[str, Union[str, os.PathLike, 'pd.DataFrame', bytes]]]=None) -> EmailMessage:
  83. """Send an email.
  84. Parameters
  85. ----------
  86. subject : str
  87. Subject of the email.
  88. sender : str, optional
  89. Email address the email is sent from.
  90. Note that some email services might not
  91. respect changing sender address
  92. (for example Gmail).
  93. receivers : list, optional
  94. Receivers of the email.
  95. cc : list, optional
  96. Cc or Carbon Copy of the email.
  97. Additional recipients of the email.
  98. bcc : list, optional
  99. Blind Carbon Copy of the email.
  100. Additional recipients of the email that
  101. don't see who else got the email.
  102. html : str, optional
  103. HTML body of the email. This is processed
  104. by Jinja and may contain loops, parametrization
  105. etc. See `Jinja documentation <https://jinja.palletsprojects.com>`_.
  106. text : str, optional
  107. Text body of the email. This is processed
  108. by Jinja and may contain loops, parametrization
  109. etc. See `Jinja documentation <https://jinja.palletsprojects.com>`_.
  110. html_template : str, optional
  111. Name of the HTML template loaded using Jinja environment specified
  112. in ``templates_html`` attribute. Specify either ``html`` or ``html_template``.
  113. text_template : str, optional
  114. Name of the text template loaded using Jinja environment specified
  115. in ``templates_text`` attribute. Specify either ``text`` or ``text_template``.
  116. body_images : dict of bytes, dict of path-like, dict of plt Figure, dict of PIL Image, optional
  117. HTML images to embed with the html. The key should be
  118. as Jinja variables in the html and the values represent
  119. images (path to an image, bytes of an image or image object).
  120. body_tables : dict of Pandas dataframes, optional
  121. HTML tables to embed with the html. The key should be
  122. as Jinja variables in the html and the values are Pandas
  123. DataFrames.
  124. body_params : dict, optional
  125. Extra Jinja parameters passed to the HTML and text bodies.
  126. attachments : dict, optional
  127. Attachments of the email. If dict value is string, the attachment content
  128. is the string itself. If path, the attachment is the content of the path's file.
  129. If dataframe, the dataframe is turned to bytes or text according to the
  130. file extension in dict key.
  131. Examples
  132. --------
  133. Simple example:
  134. .. code-block:: python
  135. from redmail import EmailSender
  136. email = EmailSender(
  137. host='localhost',
  138. port=0,
  139. user_name='me@example.com',
  140. password='<PASSWORD>'
  141. )
  142. email.send(
  143. subject="An email",
  144. sender="me@example.com",
  145. receivers=['you@example.com'],
  146. test="Hi, this is an email.",
  147. html="<h1>Hi, </h1><p>this is an email.</p>"
  148. )
  149. See more examples from :ref:`docs <examples>`
  150. Returns
  151. -------
  152. EmailMessage
  153. Email message.
  154. Notes
  155. -----
  156. See also `Jinja documentation <https://jinja.palletsprojects.com>`_
  157. for utilizing Jinja in ``html`` and ``text`` arguments or for using
  158. Jinja templates with ``html_template`` and ``text_template`` arguments.
  159. """
  160. msg = self.get_message(
  161. subject=subject,
  162. sender=sender,
  163. receivers=receivers,
  164. cc=cc,
  165. bcc=bcc,
  166. html=html,
  167. text=text,
  168. html_template=html_template,
  169. text_template=text_template,
  170. body_images=body_images,
  171. body_tables=body_tables,
  172. body_params=body_params,
  173. attachments=attachments,
  174. )
  175. self.send_message(msg)
  176. return msg
  177. def get_message(self,
  178. subject:Optional[str]=None,
  179. sender:Optional[str]=None,
  180. receivers:Union[List[str], str, None]=None,
  181. cc:Union[List[str], str, None]=None,
  182. bcc:Union[List[str], str, None]=None,
  183. html:Optional[str]=None,
  184. text:Optional[str]=None,
  185. html_template:Optional[str]=None,
  186. text_template:Optional[str]=None,
  187. body_images:Optional[Dict[str, Union[str, bytes, 'plt.Figure', 'Image']]]=None,
  188. body_tables:Optional[Dict[str, 'pd.DataFrame']]=None,
  189. body_params:Optional[Dict[str, Any]]=None,
  190. attachments:Optional[Dict[str, Union[str, os.PathLike, 'pd.DataFrame', bytes]]]=None) -> EmailMessage:
  191. """Get the email message"""
  192. subject = subject or self.subject
  193. sender = self.get_sender(sender)
  194. receivers = self.get_receivers(receivers)
  195. cc = self.get_cc(cc)
  196. bcc = self.get_bcc(bcc)
  197. html = html or self.html
  198. text = text or self.text
  199. html_template = html_template or self.html_template
  200. text_template = text_template or self.text_template
  201. if subject is None:
  202. raise ValueError("Email must have a subject")
  203. msg = self._create_body(
  204. subject=subject,
  205. sender=sender,
  206. receivers=receivers,
  207. cc=cc,
  208. bcc=bcc,
  209. )
  210. if text is not None or text_template is not None:
  211. body = TextBody(
  212. template=self.get_text_template(text_template),
  213. table_template=self.get_text_table_template(),
  214. )
  215. body.attach(
  216. msg,
  217. text,
  218. tables=body_tables,
  219. jinja_params=self.get_text_params(extra=body_params, sender=sender),
  220. )
  221. if html is not None or html_template is not None:
  222. body = HTMLBody(
  223. template=self.get_html_template(html_template),
  224. table_template=self.get_html_table_template(),
  225. )
  226. body.attach(
  227. msg,
  228. html=html,
  229. images=body_images,
  230. tables=body_tables,
  231. jinja_params=self.get_html_params(extra=body_params, sender=sender)
  232. )
  233. if attachments:
  234. att = Attachments(attachments, encoding=self.attachment_encoding)
  235. att.attach(msg)
  236. return msg
  237. def get_receivers(self, receivers:Union[list, str, None]) -> Union[List[str], None]:
  238. """Get receivers of the email"""
  239. return receivers or self.receivers
  240. def get_cc(self, cc:Union[list, str, None]) -> Union[List[str], None]:
  241. """Get carbon copy (cc) of the email"""
  242. return cc or self.cc
  243. def get_bcc(self, bcc:Union[list, str, None]) -> Union[List[str], None]:
  244. """Get blind carbon copy (bcc) of the email"""
  245. return bcc or self.bcc
  246. def get_sender(self, sender:Union[str, None]) -> str:
  247. """Get sender of the email"""
  248. return sender or self.sender or self.user_name
  249. def _create_body(self, subject, sender, receivers=None, cc=None, bcc=None) -> EmailMessage:
  250. msg = EmailMessage()
  251. msg["from"] = sender
  252. msg["subject"] = subject
  253. # To whoom the email goes
  254. if receivers:
  255. msg["to"] = receivers
  256. if cc:
  257. msg['cc'] = cc
  258. if bcc:
  259. msg['bcc'] = bcc
  260. return msg
  261. def send_message(self, msg:EmailMessage):
  262. "Send the created message"
  263. user = self.user_name
  264. password = self.password
  265. server = self._cls_smtp_server(self.host, self.port)
  266. server.starttls()
  267. if user is not None or password is not None:
  268. server.login(user, password)
  269. server.send_message(msg)
  270. server.quit()
  271. def get_params(self, sender:str) -> Dict[str, Any]:
  272. "Get Jinja parametes passed to both text and html bodies"
  273. # TODO: Add receivers to params
  274. return {
  275. "node": node(),
  276. "user": getuser(),
  277. "now": datetime.datetime.now(),
  278. "sender": EmailAddress(sender),
  279. }
  280. def get_html_params(self, extra:Optional[dict]=None, **kwargs) -> Dict[str, Any]:
  281. "Get Jinja parameters passed to HTML body"
  282. params = self.get_params(**kwargs)
  283. params.update({
  284. "error": Error(content_type='html-inline')
  285. })
  286. if extra:
  287. params.update(extra)
  288. return params
  289. def get_text_params(self, extra:Optional[dict]=None, **kwargs) -> Dict[str, Any]:
  290. "Get Jinja parameters passed to text body"
  291. params = self.get_params(**kwargs)
  292. params.update({
  293. "error": Error(content_type='text')
  294. })
  295. if extra:
  296. params.update(extra)
  297. return params
  298. def get_html_table_template(self, layout:Optional[str]=None) -> Union[jinja2.Template, None]:
  299. "Get Jinja template for tables in HTML body"
  300. layout = self.default_html_theme if layout is None else layout
  301. if layout is None:
  302. return None
  303. return self.templates_html_table.get_template(layout)
  304. def get_html_template(self, layout:Optional[str]=None) -> Union[jinja2.Template, None]:
  305. "Get pre-made Jinja template for HTML body"
  306. if layout is None:
  307. return None
  308. return self.templates_html.get_template(layout)
  309. def get_text_table_template(self, layout:Optional[str]=None) -> jinja2.Template:
  310. "Get Jinja template for tables in text body"
  311. layout = self.default_text_theme if layout is None else layout
  312. if layout is None:
  313. return None
  314. return self.templates_text_table.get_template(layout)
  315. def get_text_template(self, layout:Optional[str]=None) -> jinja2.Template:
  316. "Get pre-made Jinja template for text body"
  317. if layout is None:
  318. return None
  319. return self.templates_text.get_template(layout)
  320. def set_template_paths(self,
  321. html:Union[str, os.PathLike, None]=None,
  322. text:Union[str, os.PathLike, None]=None,
  323. html_table:Union[str, os.PathLike, None]=None,
  324. text_table:Union[str, os.PathLike, None]=None):
  325. """Create Jinja envs for body templates using given paths
  326. This is a shortcut for manually setting them:
  327. .. code-block:: python
  328. sender.templates_html = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  329. sender.templates_text = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  330. sender.templates_html_table = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  331. sender.templates_text_table = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  332. """
  333. if html is not None:
  334. self.templates_html = jinja2.Environment(loader=jinja2.FileSystemLoader(html))
  335. if text is not None:
  336. self.templates_text = jinja2.Environment(loader=jinja2.FileSystemLoader(text))
  337. if html_table is not None:
  338. self.templates_html_table = jinja2.Environment(loader=jinja2.FileSystemLoader(html_table))
  339. if text_table is not None:
  340. self.templates_text_table = jinja2.Environment(loader=jinja2.FileSystemLoader(text_table))