sender.py 19 KB

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