sender.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. cls_smtp : smtplib.SMTP
  32. SMTP class to use for connection. See options
  33. from `Python smtplib docs <https://docs.python.org/3/library/smtplib.html>`_.
  34. use_starttls : bool
  35. Whether to use `STARTTLS <https://en.wikipedia.org/wiki/Opportunistic_TLS>`_
  36. when connecting to the SMTP server.
  37. **kwargs : dict
  38. Additional keyword arguments are passed to initiation in ``cls_smtp``.
  39. These are stored as attribute ``kws_smtp``
  40. Attributes
  41. ----------
  42. sender : str
  43. Address for sending emails if it is not specified
  44. in the send method.
  45. receivers : list of str
  46. Addresses to send emails if not specified
  47. in the send method.
  48. cc : list of str
  49. Carbon copies of emails if not specified
  50. in the send method.
  51. bcc : list of str
  52. Blind carbon copies of emails if not specified
  53. in the send method.
  54. subject : str
  55. Subject of emails if not specified
  56. in the send method.
  57. text : str
  58. Text body of emails if not specified
  59. in the send method.
  60. html : str
  61. HTML body of emails if not specified
  62. in the send method.
  63. text_template : str
  64. Name of the template to use as the text body of emails
  65. if not specified in the send method.
  66. html_template : str
  67. Name of the template to use as the HTML body of emails
  68. if not specified in the send method.
  69. templates_html : jinja2.Environment
  70. Jinja environment used for loading HTML templates
  71. if ``html_template`` is specified in send.
  72. templates_text : jinja2.Environment
  73. Jinja environment used for loading text templates
  74. if ``text_template`` is specified in send.
  75. default_html_theme : str
  76. Jinja template from ``templates_html_table``
  77. used for styling tables for HTML body.
  78. default_text_theme : str
  79. Jinja template from ``templates_text_table``
  80. used for styling tables for text body.
  81. templates_html_table : jinja2.Environment
  82. Jinja environment used for loading templates
  83. for table styling for HTML bodies.
  84. templates_text_table : jinja2.Environment
  85. Jinja environment used for loading templates
  86. for table styling for text bodies.
  87. Examples
  88. --------
  89. .. code-block:: python
  90. email = EmailSender(server="smtp.mymail.com", port=123)
  91. email.send(
  92. subject="Example Email",
  93. sender="me@example.com",
  94. receivers=["you@example.com"],
  95. )
  96. """
  97. default_html_theme = "modest.html"
  98. default_text_theme = "pandas.txt"
  99. templates_html = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates/html")))
  100. templates_html_table = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates/html/table")))
  101. templates_text = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates/text")))
  102. templates_text_table = jinja2.Environment(loader=jinja2.FileSystemLoader(str(Path(__file__).parent / "templates/text/table")))
  103. # Set globals
  104. templates_html_table.globals["get_span"] = get_span
  105. templates_text_table.globals["get_span"] = get_span
  106. templates_html_table.globals["is_last_group_row"] = is_last_group_row
  107. templates_text_table.globals["is_last_group_row"] = is_last_group_row
  108. attachment_encoding = 'UTF-8'
  109. def __init__(self, host:str, port:int, user_name:str=None, password:str=None, cls_smtp:smtplib.SMTP=smtplib.SMTP, use_starttls:bool=True, **kwargs):
  110. self.host = host
  111. self.port = port
  112. self.user_name = user_name
  113. self.password = password
  114. # Defaults
  115. self.sender = None
  116. self.receivers = None
  117. self.cc = None
  118. self.bcc = None
  119. self.subject = None
  120. self.text = None
  121. self.html = None
  122. self.html_template = None
  123. self.text_template = None
  124. self.use_starttls = use_starttls
  125. self.cls_smtp = cls_smtp
  126. self.kws_smtp = kwargs
  127. def send(self,
  128. subject:Optional[str]=None,
  129. sender:Optional[str]=None,
  130. receivers:Union[List[str], str, None]=None,
  131. cc:Union[List[str], str, None]=None,
  132. bcc:Union[List[str], str, None]=None,
  133. html:Optional[str]=None,
  134. text:Optional[str]=None,
  135. html_template:Optional[str]=None,
  136. text_template:Optional[str]=None,
  137. body_images:Optional[Dict[str, Union[str, bytes, 'plt.Figure', 'Image']]]=None,
  138. body_tables:Optional[Dict[str, 'pd.DataFrame']]=None,
  139. body_params:Optional[Dict[str, Any]]=None,
  140. attachments:Optional[Dict[str, Union[str, os.PathLike, 'pd.DataFrame', bytes]]]=None) -> EmailMessage:
  141. """Send an email.
  142. Parameters
  143. ----------
  144. subject : str
  145. Subject of the email.
  146. sender : str, optional
  147. Email address the email is sent from.
  148. Note that some email services might not
  149. respect changing sender address
  150. (for example Gmail).
  151. receivers : list, optional
  152. Receivers of the email.
  153. cc : list, optional
  154. Cc or Carbon Copy of the email.
  155. Additional recipients of the email.
  156. bcc : list, optional
  157. Blind Carbon Copy of the email.
  158. Additional recipients of the email that
  159. don't see who else got the email.
  160. html : str, optional
  161. HTML body of the email. This is processed
  162. by Jinja and may contain loops, parametrization
  163. etc. See `Jinja documentation <https://jinja.palletsprojects.com>`_.
  164. text : str, optional
  165. Text body of the email. This is processed
  166. by Jinja and may contain loops, parametrization
  167. etc. See `Jinja documentation <https://jinja.palletsprojects.com>`_.
  168. html_template : str, optional
  169. Name of the HTML template loaded using Jinja environment specified
  170. in ``templates_html`` attribute. Specify either ``html`` or ``html_template``.
  171. text_template : str, optional
  172. Name of the text template loaded using Jinja environment specified
  173. in ``templates_text`` attribute. Specify either ``text`` or ``text_template``.
  174. body_images : dict of bytes, dict of path-like, dict of plt Figure, dict of PIL Image, optional
  175. HTML images to embed with the html. The key should be
  176. as Jinja variables in the html and the values represent
  177. images (path to an image, bytes of an image or image object).
  178. body_tables : dict of Pandas dataframes, optional
  179. HTML tables to embed with the html. The key should be
  180. as Jinja variables in the html and the values are Pandas
  181. DataFrames.
  182. body_params : dict, optional
  183. Extra Jinja parameters passed to the HTML and text bodies.
  184. attachments : dict, optional
  185. Attachments of the email. If dict value is string, the attachment content
  186. is the string itself. If path, the attachment is the content of the path's file.
  187. If dataframe, the dataframe is turned to bytes or text according to the
  188. file extension in dict key.
  189. Examples
  190. --------
  191. Simple example:
  192. .. code-block:: python
  193. from redmail import EmailSender
  194. email = EmailSender(
  195. host='localhost',
  196. port=0,
  197. user_name='me@example.com',
  198. password='<PASSWORD>'
  199. )
  200. email.send(
  201. subject="An email",
  202. sender="me@example.com",
  203. receivers=['you@example.com'],
  204. test="Hi, this is an email.",
  205. html="<h1>Hi, </h1><p>this is an email.</p>"
  206. )
  207. See more examples from :ref:`docs <examples>`
  208. Returns
  209. -------
  210. EmailMessage
  211. Email message.
  212. Notes
  213. -----
  214. See also `Jinja documentation <https://jinja.palletsprojects.com>`_
  215. for utilizing Jinja in ``html`` and ``text`` arguments or for using
  216. Jinja templates with ``html_template`` and ``text_template`` arguments.
  217. """
  218. msg = self.get_message(
  219. subject=subject,
  220. sender=sender,
  221. receivers=receivers,
  222. cc=cc,
  223. bcc=bcc,
  224. html=html,
  225. text=text,
  226. html_template=html_template,
  227. text_template=text_template,
  228. body_images=body_images,
  229. body_tables=body_tables,
  230. body_params=body_params,
  231. attachments=attachments,
  232. )
  233. self.send_message(msg)
  234. return msg
  235. def get_message(self,
  236. subject:Optional[str]=None,
  237. sender:Optional[str]=None,
  238. receivers:Union[List[str], str, None]=None,
  239. cc:Union[List[str], str, None]=None,
  240. bcc:Union[List[str], str, None]=None,
  241. html:Optional[str]=None,
  242. text:Optional[str]=None,
  243. html_template:Optional[str]=None,
  244. text_template:Optional[str]=None,
  245. body_images:Optional[Dict[str, Union[str, bytes, 'plt.Figure', 'Image']]]=None,
  246. body_tables:Optional[Dict[str, 'pd.DataFrame']]=None,
  247. body_params:Optional[Dict[str, Any]]=None,
  248. attachments:Optional[Dict[str, Union[str, os.PathLike, 'pd.DataFrame', bytes]]]=None) -> EmailMessage:
  249. """Get the email message"""
  250. subject = subject or self.subject
  251. sender = self.get_sender(sender)
  252. receivers = self.get_receivers(receivers)
  253. cc = self.get_cc(cc)
  254. bcc = self.get_bcc(bcc)
  255. html = html or self.html
  256. text = text or self.text
  257. html_template = html_template or self.html_template
  258. text_template = text_template or self.text_template
  259. if subject is None:
  260. raise ValueError("Email must have a subject")
  261. msg = self._create_body(
  262. subject=subject,
  263. sender=sender,
  264. receivers=receivers,
  265. cc=cc,
  266. bcc=bcc,
  267. )
  268. if text is not None or text_template is not None:
  269. body = TextBody(
  270. template=self.get_text_template(text_template),
  271. table_template=self.get_text_table_template(),
  272. )
  273. body.attach(
  274. msg,
  275. text,
  276. tables=body_tables,
  277. jinja_params=self.get_text_params(extra=body_params, sender=sender),
  278. )
  279. if html is not None or html_template is not None:
  280. body = HTMLBody(
  281. template=self.get_html_template(html_template),
  282. table_template=self.get_html_table_template(),
  283. )
  284. body.attach(
  285. msg,
  286. html=html,
  287. images=body_images,
  288. tables=body_tables,
  289. jinja_params=self.get_html_params(extra=body_params, sender=sender)
  290. )
  291. if attachments:
  292. att = Attachments(attachments, encoding=self.attachment_encoding)
  293. att.attach(msg)
  294. return msg
  295. def get_receivers(self, receivers:Union[list, str, None]) -> Union[List[str], None]:
  296. """Get receivers of the email"""
  297. return receivers or self.receivers
  298. def get_cc(self, cc:Union[list, str, None]) -> Union[List[str], None]:
  299. """Get carbon copy (cc) of the email"""
  300. return cc or self.cc
  301. def get_bcc(self, bcc:Union[list, str, None]) -> Union[List[str], None]:
  302. """Get blind carbon copy (bcc) of the email"""
  303. return bcc or self.bcc
  304. def get_sender(self, sender:Union[str, None]) -> str:
  305. """Get sender of the email"""
  306. return sender or self.sender or self.user_name
  307. def _create_body(self, subject, sender, receivers=None, cc=None, bcc=None) -> EmailMessage:
  308. msg = EmailMessage()
  309. msg["from"] = sender
  310. msg["subject"] = subject
  311. # To whoom the email goes
  312. if receivers:
  313. msg["to"] = receivers
  314. if cc:
  315. msg['cc'] = cc
  316. if bcc:
  317. msg['bcc'] = bcc
  318. return msg
  319. def send_message(self, msg:EmailMessage):
  320. "Send the created message"
  321. server = self.connect()
  322. server.send_message(msg)
  323. server.quit()
  324. def connect(self) -> smtplib.SMTP:
  325. "Connect to the SMTP Server"
  326. user = self.user_name
  327. password = self.password
  328. server = self.cls_smtp(self.host, self.port, **self.kws_smtp)
  329. if self.use_starttls:
  330. server.starttls()
  331. if user is not None or password is not None:
  332. server.login(user, password)
  333. return server
  334. def get_params(self, sender:str) -> Dict[str, Any]:
  335. "Get Jinja parametes passed to both text and html bodies"
  336. # TODO: Add receivers to params
  337. return {
  338. "node": node(),
  339. "user": getuser(),
  340. "now": datetime.datetime.now(),
  341. "sender": EmailAddress(sender),
  342. }
  343. def get_html_params(self, extra:Optional[dict]=None, **kwargs) -> Dict[str, Any]:
  344. "Get Jinja parameters passed to HTML body"
  345. params = self.get_params(**kwargs)
  346. params.update({
  347. "error": Error(content_type='html-inline')
  348. })
  349. if extra:
  350. params.update(extra)
  351. return params
  352. def get_text_params(self, extra:Optional[dict]=None, **kwargs) -> Dict[str, Any]:
  353. "Get Jinja parameters passed to text body"
  354. params = self.get_params(**kwargs)
  355. params.update({
  356. "error": Error(content_type='text')
  357. })
  358. if extra:
  359. params.update(extra)
  360. return params
  361. def get_html_table_template(self, layout:Optional[str]=None) -> Union[jinja2.Template, None]:
  362. "Get Jinja template for tables in HTML body"
  363. layout = self.default_html_theme if layout is None else layout
  364. if layout is None:
  365. return None
  366. return self.templates_html_table.get_template(layout)
  367. def get_html_template(self, layout:Optional[str]=None) -> Union[jinja2.Template, None]:
  368. "Get pre-made Jinja template for HTML body"
  369. if layout is None:
  370. return None
  371. return self.templates_html.get_template(layout)
  372. def get_text_table_template(self, layout:Optional[str]=None) -> jinja2.Template:
  373. "Get Jinja template for tables in text body"
  374. layout = self.default_text_theme if layout is None else layout
  375. if layout is None:
  376. return None
  377. return self.templates_text_table.get_template(layout)
  378. def get_text_template(self, layout:Optional[str]=None) -> jinja2.Template:
  379. "Get pre-made Jinja template for text body"
  380. if layout is None:
  381. return None
  382. return self.templates_text.get_template(layout)
  383. def set_template_paths(self,
  384. html:Union[str, os.PathLike, None]=None,
  385. text:Union[str, os.PathLike, None]=None,
  386. html_table:Union[str, os.PathLike, None]=None,
  387. text_table:Union[str, os.PathLike, None]=None):
  388. """Create Jinja envs for body templates using given paths
  389. This is a shortcut for manually setting them:
  390. .. code-block:: python
  391. sender.templates_html = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  392. sender.templates_text = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  393. sender.templates_html_table = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  394. sender.templates_text_table = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  395. """
  396. if html is not None:
  397. self.templates_html = jinja2.Environment(loader=jinja2.FileSystemLoader(html))
  398. if text is not None:
  399. self.templates_text = jinja2.Environment(loader=jinja2.FileSystemLoader(text))
  400. if html_table is not None:
  401. self.templates_html_table = jinja2.Environment(loader=jinja2.FileSystemLoader(html_table))
  402. if text_table is not None:
  403. self.templates_text_table = jinja2.Environment(loader=jinja2.FileSystemLoader(text_table))