Home >Backend Development >Python Tutorial >How to configure email sending log in Python?

How to configure email sending log in Python?

PHPz
PHPzforward
2023-04-26 17:28:081718browse

How to configure email sending log in Python?

Someone asked in the group a few days ago and said something about Python configuration email sending log. I feel that it is quite knowledgeable, so I will record it here to avoid pitfalls in the future.

  • We can use Python's logging.handlers.SMTPHandler method to send logs to the specified mailbox. I used to use 163 mailbox configuration parameters before and I can use it with confidence, but when I use QQ's corporate mailbox, I always get an error and it always says that the login has timed out.

How to configure email sending log in Python?

#Finally, I found the reason by reading the source code of logging. Logging supports TLS connections by default. QQ Enterprise Mailbox and Gmail both use SSL connections.

How to configure email sending log in Python?

  • Finally attach a simple configuration
# logging.conf完整配置
[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), 'username@163.com', ['somebody01@example.com','somebody02@example.com'], 'Test SMTPHandler', ('username', 'password'))
python
# 邮件测试例子
import logging
import logging.config
logging.config.fileConfig("logging.conf")
logger = logging.getLogger('test')
logger.info('hello body ~')


The above is the detailed content of How to configure email sending log in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete