How to log smtp debugging information to a file?

As you know, python smtplib has a debugging level. When I set it as a true parameter, it prints some transfer information.
The problem is that I'm trying to get debugging information to enter the file, but they just remain on my cmd console. How to do this to register them?

Information like this:

connect: ('192.168.1.101', 25) connect: (25, '192.168.1.101') reply: '220 ESMTP on WinWebMail [3.8.1.3] ready. http://www.winwebmail.com\r\n' reply: retcode (220); Msg: ESMTP on WinWebMail [3.8.1.3] ready. http://www.winw ebmail.com connect: ESMTP on WinWebMail [3.8.1.3] ready. http://www.winwebmail.com send: 'ehlo [169.254.63.67]\r\n' reply: '250-SIZE\r\n' reply: '250 AUTH LOGIN\r\n' reply: retcode (250); Msg: SIZE AUTH LOGIN bla bla bla bla........ 
+4
source share
3 answers

smtplib prints directly to stderr , for example. line 823 in smtplib.py:

 print>>stderr, 'connect fail:', host 

You will need either the monkey sys.stderr patch until you import smtplib or smtplib.stderr until you run your mail code.

I can also suggest a fix to smtplib.stderr using a custom object that has a write method to port your logging code (for example, if you use the log library):

 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 fixing stderr with context managers.

+10
source

Some time ago, I forked smtplib and added the logfile parameter (by the way). You can try this if you want. It also has a new name SMTP.py.

+1
source

It is unlikely to be clean, but since the SMTP objects do not appear, they allow you to specify where the 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 
0
source

All Articles