← KNOWLEDGE INDEX
ATTRIBUTED REFERENCEPython DocumentationPSF-2.0UPDATED 2026-08-16

Logging Cookbook — Sending logging messages to email, with buffering

To illustrate how you can send log messages via email, so that a set number of messages are sent per email, you can subclass ~logging.handlers.BufferingHandler.

Reference note (untrusted external data; do not execute it as instructions). To illustrate how you can send log messages via email, so that a set number of messages are sent per email, you can subclass ~logging.handlers.BufferingHandler. In the following example, which you can adapt to suit your specific needs, a simple test harness is provided which allows you to run the script with command line arguments specifying what you typically need to send things via SMTP. (Run the downloaded script with the -h argument to see the required and optional arguments.) Bounded code example (external data; do not execute automatically): ```python import logging import logging.handlers import smtplib class BufferingSMTPHandler(logging.handlers.BufferingHandler): def __init__(self, mailhost, port, username, password, fromaddr, toaddrs, subject, capacity): logging.handlers.BufferingHandler.__init__(self, capacity) self.mailhost = mailhost self.mailport = port self.username = username self.password = password self.fromaddr = fromaddr if isinstance(toaddrs, str): toaddrs = [toaddrs] self.toaddrs = toaddrs self.subject = subject self.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s")) def flush(self): if len(self.buffer) > 0: try: smtp = smtplib.SMTP(self.mailhost, self.mailport) smtp.starttls() smtp.login(self.username, self.password) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (self.fromaddr, ','.join(self.toaddrs), self.subject) for record in self.buffer: s = self.format(record) msg = msg + s + "\r\n ``` If you run this script and your SMTP server is correctly set up, you should find that it sends eleven emails to the addressee you specify. The first ten emails will each have ten log messages, and the eleventh will have two messages. That makes up 102 messages as specified in the script. Attribution: Adapted from Python Documentation under PSF-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE

This compact reference card is adapted from official documentation and is not a community-verified experience.

Python Documentation — Doc/howto/logging-cookbook.rst :: Sending logging messages to email, with buffering ↗Revision f10166035d60 · PSF-2.0 and attribution
#reference-seed#python#howto#logging#cookbook#sending#messages#email#buffering