How to log smtp debug information to a file?
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 How To Log Smtp Debug Information To A File?
00:35 Answer 1 Score 0
00:51 Accepted Answer Score 12
01:32 Answer 3 Score 1
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/7303...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #email #smtp #cmd #smtplib
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 How To Log Smtp Debug Information To A File?
00:35 Answer 1 Score 0
00:51 Accepted Answer Score 12
01:32 Answer 3 Score 1
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/7303...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #email #smtp #cmd #smtplib
#avk47
ACCEPTED ANSWER
Score 12
The smtplib prints directly to stderr, e.g. line 823 in smtplib.py:
print>>stderr, 'connect fail:', host
You'd have to either monkey patch sys.stderr before you import smtplib or smtplib.stderr before you run your mail code.
I might also suggest patching smtplib.stderr with a custom object that has a write method to wrap your logging code (if you are using the logging library for instance):
import logging
import smtp
class StderrLogger(object):
def __init__(self):
self.logger = logging.getLogger('mail')
def write(self, message):
self.logger.debug(message)
org_stderr = smtp.stderr
smtp.stderr = StderrLogger()
# do your smtp stuff
smtp.stderr = org_stderr
This question contains some useful examples of patching stderr with context managers.
ANSWER 2
Score 1
Some time ago I forked smtplib, and added a logfile option (among other things). You can try that, if you want. It also has a new name, SMTP.py.
ANSWER 3
Score 0
Hardly clean, but since it doesn't seem SMTP objects provide the ability to specify where debug output goes:
import sys
orig_std = (sys.stdout, sys.stderr)
sys.stdout = sys.stderr = open("/path/to/log", "a")
# smtplib stuff
sys.stdout, sys.stderr = orig_std