Advertisement
DeaD_EyE

send uncaught exceptions via email

Aug 30th, 2021 (edited)
1,493
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. """
  4. Just import this module and change the settings.
  5. Uncaught Exceptions were sent via E-Mail with a thread.
  6.  
  7. The emails package is required.
  8. """
  9.  
  10. import sys
  11. import traceback
  12. from pathlib import Path
  13. from threading import Thread
  14.  
  15. try:
  16.     from emails import Message
  17. except ImportError:
  18.     raise SystemExit("Please install the emails package\n\npip3 install emails")
  19.  
  20.  
  21. class Sender:
  22.     def __init__(
  23.         self, mail_from, mail_to, username, password, host, port, tls, timeout
  24.     ):
  25.         self.smtp = {
  26.             "user": username,
  27.             "password": password,
  28.             "host": host,
  29.             "port": port,
  30.             "timeout": timeout,
  31.             "tls": tls,
  32.         }
  33.         self.mail_to = mail_to
  34.         self.mail_from = mail_from
  35.  
  36.     def send(self, subject, text):
  37.         Thread(target=self._send, args=(subject, text)).start()
  38.  
  39.     def _send(self, subject, text):
  40.         return (
  41.             Message(
  42.                 subject=subject,
  43.                 mail_from=self.mail_from,
  44.                 mail_to=self.mail_to,
  45.                 text=text,
  46.             )
  47.             .send(smtp=self.smtp)
  48.             .error
  49.         )
  50.  
  51.  
  52. def hook(exctype, value, tb):
  53.     tb = "\n".join(traceback.format_exception(exctype, value, tb))
  54.     _sender.send(f"Exception: {exctype}", f"Value: {value}\nTraceback: {tb}\n")
  55.  
  56.  
  57. MAIL_FROM = "mail@domain.tld"
  58. MAIL_TO = "mail@domain.tld"
  59. HOST = "smtp.domain.tld"
  60. PORT = 587
  61. TLS = True
  62. TIMEOUT = 5
  63. USERNAME = "mail@domain.tld"
  64. # Password could be stored in a file or you put it into the source,
  65. # which is not a good idea
  66. PASSWORD = Path.home().joinpath(".config/.emailpw").read_text().rstrip()
  67.  
  68. # make an instance of Sender
  69. _sender = Sender(MAIL_FROM, MAIL_TO, USERNAME, PASSWORD, HOST, PORT, TLS, TIMEOUT)
  70.  
  71. # replacing the sys.excpthook, which is called, if an uncaught exception occurs.
  72. # the function hook is the replacement
  73.  
  74. sys.excepthook = hook
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement