Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log smtp debug information to a file?

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........
like image 505
soasme Avatar asked Sep 05 '11 02:09

soasme


2 Answers

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.

like image 117
Mark Gemmill Avatar answered Oct 01 '22 12:10

Mark Gemmill


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.

like image 45
Keith Avatar answered Oct 01 '22 12:10

Keith