logging SMTPHandler and Authentication
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Apr 30 21:41:15 EDT 2007
En Mon, 30 Apr 2007 21:08:34 -0300, <james.p.news at gmail.com> escribió:
> I'm new to Python, but I've been thrown into coding a pretty
> complicated regression testing script. I need to email the log of the
> daily test to the code owners. I thought I could use SMTPHandler for
> this, but our email system requires authentication. I have not been
> able to figure out how to log in using SMTPHandler. I found the
> following post on comp.lang.python:
>
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/ef873c79157b8624/cdb67687e507c974?lnk=gst&q=SMTPHandler+authentication&rnum=1#cdb67687e507c974
>
> However, I haven't been able to translate this to anything I can use.
> I've also looked at the source code for the SMTPHandler, but I don't
> want to edit that.
Unfortunately -and despite what's said on that post- SMTPHandler does
*not* provide any hook to customize the way it sends the message. The SMTP
instance used internally is not available so you can't call its login()
method from the outside. If you don't want to edit the sources, you could
inherit from SMTPHandler, copy the emit() implementation and add the
missing login() call:
--- begin code ---
import logging, logging.handlers, string
class SMTPHandlerWithAuth(logging.handlers.SMTPHandler):
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
import smtplib
try:
from email.Utils import formatdate
except:
formatdate = self.date_time
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate:
%s\r\n\r\n%s" % (
self.fromaddr,
string.join(self.toaddrs, ","),
self.getSubject(record),
formatdate(), msg)
# ADD THE FOLLOWING LINE:
smtp.login(username, password)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
rootLogger = logging.getLogger('')
smtpHandler = SMTPHandlerWithAuth(('localhost',587),
'from_address at xxx.com', 'to_address at xxx.com', "Error subject")
rootLogger.addHandler(smtpHandler)
logging.error('This is an error message that should be sent by mail.')
--- end code ---
--
Gabriel Genellina
More information about the Python-list
mailing list