sender.py 21 KB

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