1
0

sender.py 17 KB

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