sender.py 22 KB

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