1
0

sender.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. from copy import copy
  2. from email.message import EmailMessage
  3. from email.utils import make_msgid
  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.headers = None
  140. self.text = None
  141. self.html = None
  142. self.html_template = None
  143. self.text_template = None
  144. self.use_jinja = True
  145. self.use_starttls = use_starttls
  146. self.cls_smtp = cls_smtp
  147. self.kws_smtp = kwargs
  148. self.connection = None
  149. def send(self,
  150. subject:Optional[str]=None,
  151. sender:Optional[str]=None,
  152. receivers:Union[List[str], str, None]=None,
  153. cc:Union[List[str], str, None]=None,
  154. bcc:Union[List[str], str, None]=None,
  155. headers:Optional[Dict[str, str]]=None,
  156. html:Optional[str]=None,
  157. text:Optional[str]=None,
  158. html_template:Optional[str]=None,
  159. text_template:Optional[str]=None,
  160. body_images:Optional[Dict[str, Union[str, bytes, 'plt.Figure', 'Image']]]=None,
  161. body_tables:Optional[Dict[str, 'pd.DataFrame']]=None,
  162. body_params:Optional[Dict[str, Any]]=None,
  163. attachments:Optional[Dict[str, Union[str, os.PathLike, 'pd.DataFrame', bytes]]]=None) -> EmailMessage:
  164. """Send an email.
  165. Parameters
  166. ----------
  167. subject : str
  168. Subject of the email.
  169. sender : str, optional
  170. Email address the email is sent from.
  171. Note that some email services might not
  172. respect changing sender address
  173. (for example Gmail).
  174. receivers : list, optional
  175. Receivers of the email.
  176. cc : list, optional
  177. Cc or Carbon Copy of the email.
  178. Additional recipients of the email.
  179. bcc : list, optional
  180. Blind Carbon Copy of the email.
  181. Additional recipients of the email that
  182. don't see who else got the email.
  183. headers : dict, optional
  184. Additional email headers. Can be used to
  185. override already set headers.
  186. html : str, optional
  187. HTML body of the email. This is processed
  188. by Jinja and may contain loops, parametrization
  189. etc. See `Jinja documentation <https://jinja.palletsprojects.com>`_.
  190. text : str, optional
  191. Text body of the email. This is processed
  192. by Jinja and may contain loops, parametrization
  193. etc. See `Jinja documentation <https://jinja.palletsprojects.com>`_.
  194. html_template : str, optional
  195. Name of the HTML template loaded using Jinja environment specified
  196. in ``templates_html`` attribute. Specify either ``html`` or ``html_template``.
  197. text_template : str, optional
  198. Name of the text template loaded using Jinja environment specified
  199. in ``templates_text`` attribute. Specify either ``text`` or ``text_template``.
  200. body_images : dict of bytes, dict of path-like, dict of plt Figure, dict of PIL Image, optional
  201. HTML images to embed with the html. The key should be
  202. as Jinja variables in the html and the values represent
  203. images (path to an image, bytes of an image or image object).
  204. body_tables : dict of Pandas dataframes, optional
  205. HTML tables to embed with the html. The key should be
  206. as Jinja variables in the html and the values are Pandas
  207. DataFrames.
  208. body_params : dict, optional
  209. Extra Jinja parameters passed to the HTML and text bodies.
  210. use_jinja : bool
  211. Use Jinja to render text/HTML. If Jinja is disabled, body content cannot be
  212. embedded, templates have no effect and body parameters do nothing.
  213. attachments : dict, optional
  214. Attachments of the email. If dict value is string, the attachment content
  215. is the string itself. If path, the attachment is the content of the path's file.
  216. If dataframe, the dataframe is turned to bytes or text according to the
  217. file extension in dict key.
  218. Examples
  219. --------
  220. Simple example:
  221. .. code-block:: python
  222. from redmail import EmailSender
  223. email = EmailSender(
  224. host='localhost',
  225. port=0,
  226. username='me@example.com',
  227. password='<PASSWORD>'
  228. )
  229. email.send(
  230. subject="An email",
  231. sender="me@example.com",
  232. receivers=['you@example.com'],
  233. text="Hi, this is an email.",
  234. html="<h1>Hi, </h1><p>this is an email.</p>"
  235. )
  236. See more examples from :ref:`docs <examples>`
  237. Returns
  238. -------
  239. EmailMessage
  240. Email message.
  241. Notes
  242. -----
  243. See also `Jinja documentation <https://jinja.palletsprojects.com>`_
  244. for utilizing Jinja in ``html`` and ``text`` arguments or for using
  245. Jinja templates with ``html_template`` and ``text_template`` arguments.
  246. """
  247. msg = self.get_message(
  248. subject=subject,
  249. sender=sender,
  250. receivers=receivers,
  251. cc=cc,
  252. bcc=bcc,
  253. headers=headers,
  254. html=html,
  255. text=text,
  256. html_template=html_template,
  257. text_template=text_template,
  258. body_images=body_images,
  259. body_tables=body_tables,
  260. body_params=body_params,
  261. attachments=attachments,
  262. )
  263. self.send_message(msg)
  264. return msg
  265. def get_message(self,
  266. subject:Optional[str]=None,
  267. sender:Optional[str]=None,
  268. receivers:Union[List[str], str, None]=None,
  269. cc:Union[List[str], str, None]=None,
  270. bcc:Union[List[str], str, None]=None,
  271. html:Optional[str]=None,
  272. text:Optional[str]=None,
  273. html_template:Optional[str]=None,
  274. text_template:Optional[str]=None,
  275. body_images:Optional[Dict[str, Union[str, bytes, 'plt.Figure', 'Image']]]=None,
  276. body_tables:Optional[Dict[str, 'pd.DataFrame']]=None,
  277. body_params:Optional[Dict[str, Any]]=None,
  278. attachments:Optional[Dict[str, Union[str, os.PathLike, 'pd.DataFrame', bytes]]]=None,
  279. headers:Optional[Dict[str, str]]=None,
  280. use_jinja=None) -> EmailMessage:
  281. """Get the email message"""
  282. subject = subject or self.subject
  283. sender = self.get_sender(sender)
  284. receivers = self.get_receivers(receivers)
  285. cc = self.get_cc(cc)
  286. bcc = self.get_bcc(bcc)
  287. headers = self.get_headers(headers)
  288. html = html or self.html
  289. text = text or self.text
  290. html_template = html_template or self.html_template
  291. text_template = text_template or self.text_template
  292. use_jinja = self.use_jinja if use_jinja is None else use_jinja
  293. if subject is None:
  294. raise ValueError("Email must have a subject")
  295. msg = self._create_body(
  296. subject=subject,
  297. sender=sender,
  298. receivers=receivers,
  299. cc=cc,
  300. bcc=bcc,
  301. headers=headers
  302. )
  303. has_text = text is not None or text_template is not None
  304. has_html = html is not None or html_template is not None
  305. has_attachments = attachments is not None
  306. if has_text:
  307. body = TextBody(
  308. template=self.get_text_template(text_template),
  309. table_template=self.get_text_table_template(),
  310. jinja_env=self.templates_text,
  311. use_jinja=use_jinja
  312. )
  313. body.attach(
  314. msg,
  315. text,
  316. tables=body_tables,
  317. jinja_params=self.get_text_params(extra=body_params, sender=sender),
  318. )
  319. if has_html:
  320. body = HTMLBody(
  321. template=self.get_html_template(html_template),
  322. table_template=self.get_html_table_template(),
  323. jinja_env=self.templates_html,
  324. use_jinja=use_jinja
  325. )
  326. body.attach(
  327. msg,
  328. html=html,
  329. images=body_images,
  330. tables=body_tables,
  331. jinja_params=self.get_html_params(extra=body_params, sender=sender)
  332. )
  333. self._set_content_type(
  334. msg,
  335. has_text=has_text,
  336. has_html=has_html,
  337. has_attachments=has_attachments,
  338. )
  339. if attachments:
  340. att = Attachments(attachments, encoding=self.attachment_encoding)
  341. att.attach(msg)
  342. return msg
  343. def get_receivers(self, receivers:Union[list, str, None]) -> Union[List[str], None]:
  344. """Get receivers of the email"""
  345. return receivers or self.receivers
  346. def get_cc(self, cc:Union[list, str, None]) -> Union[List[str], None]:
  347. """Get carbon copy (cc) of the email"""
  348. return cc or self.cc
  349. def get_bcc(self, bcc:Union[list, str, None]) -> Union[List[str], None]:
  350. """Get blind carbon copy (bcc) of the email"""
  351. return bcc or self.bcc
  352. def get_headers(self, headers:Union[Dict[str, str], None]):
  353. """Get additional headers"""
  354. return headers or self.headers
  355. def get_sender(self, sender:Union[str, None]) -> str:
  356. """Get sender of the email"""
  357. return sender or self.sender or self.username
  358. def create_message_id(self, sender:str) -> str:
  359. domain = None
  360. if sender is not None and '@' in sender:
  361. domain = sender.split("@")[1]
  362. return make_msgid(domain=domain)
  363. def _create_body(self, subject, sender, receivers=None, cc=None, bcc=None, headers=None) -> EmailMessage:
  364. msg = EmailMessage()
  365. msg["From"] = sender
  366. msg["Subject"] = subject
  367. # To whoom the email goes
  368. if receivers:
  369. msg["To"] = receivers
  370. if cc:
  371. msg['Cc'] = cc
  372. if bcc:
  373. msg['Bcc'] = bcc
  374. # Message-IDs could be produced by the first mail server
  375. # or the program sending the email (as we are doing now).
  376. # Apparently Gmail might require it as of 2022
  377. msg['Message-ID'] = self.create_message_id(sender)
  378. if headers:
  379. for key, val in headers.items():
  380. msg[key] = val
  381. return msg
  382. def _set_content_type(self, msg:EmailMessage, has_text, has_html, has_attachments):
  383. # NOTE: we don't convert emails that have only text/plain to multiplart/mixed
  384. # in order to keep the messages minimal (as often desired with simple plain text)
  385. if has_html or has_attachments:
  386. # Change the structure to multipart/mixed if possible.
  387. # This seems to be the most versatile and most unproblematic top level content-type
  388. # as otherwise content may be missing or it may be misrendered.
  389. # See: https://stackoverflow.com/a/23853079/13696660
  390. # See issues: #23, #37
  391. msg.make_mixed()
  392. def send_message(self, msg:EmailMessage):
  393. "Send the created message"
  394. if self.is_alive:
  395. self.connection.send_message(msg)
  396. else:
  397. # The connection was opened for this message
  398. # thus it is also closed with this message
  399. with self:
  400. self.connection.send_message(msg)
  401. def __enter__(self):
  402. self.connect()
  403. def __exit__(self, *args):
  404. self.close()
  405. def connect(self):
  406. "Connect to the SMTP Server"
  407. self.connection = self.get_server()
  408. def close(self):
  409. "Close (quit) the connection"
  410. if self.connection:
  411. self.connection.quit()
  412. self.connection = None
  413. def get_server(self) -> smtplib.SMTP:
  414. "Connect and get the SMTP Server"
  415. user = self.username
  416. password = self.password
  417. server = self.cls_smtp(self.host, self.port, **self.kws_smtp)
  418. if self.use_starttls:
  419. server.starttls()
  420. if user is not None or password is not None:
  421. server.login(user, password)
  422. return server
  423. @property
  424. def is_alive(self):
  425. "bool: Check if there is a connection to the SMTP server"
  426. return self.connection is not None
  427. def get_params(self, sender:str) -> Dict[str, Any]:
  428. "Get Jinja parametes passed to both text and html bodies"
  429. # TODO: Add receivers to params
  430. return {
  431. "node": node(),
  432. "user": getuser(),
  433. "now": datetime.datetime.now(),
  434. "sender": EmailAddress(sender),
  435. }
  436. def get_html_params(self, extra:Optional[dict]=None, **kwargs) -> Dict[str, Any]:
  437. "Get Jinja parameters passed to HTML body"
  438. params = self.get_params(**kwargs)
  439. params.update({
  440. "error": Error(content_type='html-inline')
  441. })
  442. if extra:
  443. params.update(extra)
  444. return params
  445. def get_text_params(self, extra:Optional[dict]=None, **kwargs) -> Dict[str, Any]:
  446. "Get Jinja parameters passed to text body"
  447. params = self.get_params(**kwargs)
  448. params.update({
  449. "error": Error(content_type='text')
  450. })
  451. if extra:
  452. params.update(extra)
  453. return params
  454. def get_html_table_template(self, layout:Optional[str]=None) -> Union[jinja2.Template, None]:
  455. "Get Jinja template for tables in HTML body"
  456. layout = self.default_html_theme if layout is None else layout
  457. if layout is None:
  458. return None
  459. return self.templates_html_table.get_template(layout)
  460. def get_html_template(self, layout:Optional[str]=None) -> Union[jinja2.Template, None]:
  461. "Get pre-made Jinja template for HTML body"
  462. if layout is None:
  463. return None
  464. return self.templates_html.get_template(layout)
  465. def get_text_table_template(self, layout:Optional[str]=None) -> jinja2.Template:
  466. "Get Jinja template for tables in text body"
  467. layout = self.default_text_theme if layout is None else layout
  468. if layout is None:
  469. return None
  470. return self.templates_text_table.get_template(layout)
  471. def get_text_template(self, layout:Optional[str]=None) -> jinja2.Template:
  472. "Get pre-made Jinja template for text body"
  473. if layout is None:
  474. return None
  475. return self.templates_text.get_template(layout)
  476. def set_template_paths(self,
  477. html:Union[str, os.PathLike, None]=None,
  478. text:Union[str, os.PathLike, None]=None,
  479. html_table:Union[str, os.PathLike, None]=None,
  480. text_table:Union[str, os.PathLike, None]=None):
  481. """Create Jinja envs for body templates using given paths
  482. This is a shortcut for manually setting them:
  483. .. code-block:: python
  484. sender.templates_html = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  485. sender.templates_text = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  486. sender.templates_html_table = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  487. sender.templates_text_table = jinja2.Environment(loader=jinja2.FileSystemLoader(...))
  488. """
  489. if html is not None:
  490. self.templates_html = jinja2.Environment(loader=jinja2.FileSystemLoader(html))
  491. if text is not None:
  492. self.templates_text = jinja2.Environment(loader=jinja2.FileSystemLoader(text))
  493. if html_table is not None:
  494. self.templates_html_table = jinja2.Environment(loader=jinja2.FileSystemLoader(html_table))
  495. if text_table is not None:
  496. self.templates_text_table = jinja2.Environment(loader=jinja2.FileSystemLoader(text_table))
  497. def copy(self) -> 'EmailSender':
  498. "Shallow copy EmailSender"
  499. return copy(self)
  500. @property
  501. def user_name(self):
  502. warnings.warn("Attribute user_name was renamed as username. Please use username instead.", FutureWarning)
  503. return self.username
  504. @user_name.setter
  505. def user_name(self, user):
  506. warnings.warn("Attribute user_name was renamed as username. Please use username instead.", FutureWarning)
  507. self.username = user