sender.py 15 KB

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