How to Send Python Logs via Email with SMTPHandler (Fix QQ Timeout)
This guide explains how to configure Python's logging.handlers.SMTPHandler to email log messages, why QQ enterprise and Gmail require SSL instead of TLS, and provides a complete logging.conf example with sample code to avoid common pitfalls.
Earlier someone asked in a group about configuring Python to send log emails; I found it insightful, so I'm documenting it here to avoid pitfalls later.
We can use Python's logging.handlers.SMTPHandler to send logs to a specified mailbox. It works smoothly with 163.com mail settings, but using QQ enterprise mail repeatedly caused a login timeout error.
By examining the logging source code, we discovered that the default logging handlers use TLS connections, while QQ enterprise mail and Gmail require SSL connections, leading to the failure.
Finally, a simple configuration is provided.
# logging.conf complete configuration
[loggers]
keys=root,test
[handlers]
keys=consoleHandler,fileHandler,testHandler
[formatters]
keys=simpleFormatter
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s - [%(filename)s:%(lineno)s]
datefmt=
[logger_root]
level=INFO
handlers=consoleHandler,fileHandler
[logger_test]
level=INFO
handlers=testHandler
qualname=test
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=simpleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=simpleFormatter
args=('log/spider_db.log', 'a')
[handler_testHandler]
class=handlers.SMTPHandler
level=INFO
formatter=simpleFormatter
args=(('smtp.163.com',25), '[email protected]', ['[email protected]','[email protected]'], 'Test SMTPHandler', ('username', 'password'))
# Email test example
import logging
import logging.config
logging.config.fileConfig("logging.conf")
logger = logging.getLogger('test')
logger.info('hello body ~')Original link: https://www.escapelife.site/posts/9730226a.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
