4

As you know, python smtplib has a debug level.When I set it a true param, it will print some send information.
The problem is, I try to get the debug info to log into a file, but They just stay on my cmd console. How can I do to log them?

Info 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........
soasme
  • 392
  • 5
  • 11

3 Answers3

11

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.

Community
  • 1
  • 1
Mark Gemmill
  • 5,889
  • 2
  • 27
  • 22
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.

Keith
  • 42,110
  • 11
  • 57
  • 76
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
Ben
  • 2,422
  • 2
  • 16
  • 23
  • I used the same way in my code, but it seems that the std redirection is only limited in the code, the stderr information write by smtplib is still in the console. And I just use a dirty way to solve it temporary: add" fsock = open('error.log', 'w') stderr = fsock" in the /lib/smtplib.py code. – soasme Sep 05 '11 at 02:55