sender.py 18 KB

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