Pregunta

The Python logging library provides a class called "SMTPHandler" that will let me e-mail myself the outputs of logging commands. I've some pasted below some example code I found on a (possibly old) website for the library. I can modify it to get it to work with either gmail or my ISP as the SMTP server, but both cases require my password. I currently know of two possible solutions:

  1. I can hardcode my password, which I'd prefer not to do, since this code finds its way onto a cloud revision control server.
  2. I can file my password away in a text file on my machine and have my code read it, which seems ugly. With a more effort I may be able to store the password encrypted, rather than as plaintext.

I'm using a Mac, and I can e-mail myself by running mail on the command line and get the e-mail just fine. I don't know what mail is doing but it may be able to get my SMTP server details from the same place that Mac Mail reads them from and then use the external SMTP server. I tried setting MAILHOST="localhost" in the Python code below and that didn't work.

Is there a better way than #1 or #2 to get these e-mails to my gmail address?

import logging, logging.handlers

MAILHOST = 'beta'
FROM     = 'log_test5@yourdomain.com'
TO       = ['arkadi_renko']
SUBJECT  = 'Test Logging email from Python logging module (non-buffering)'

def main():
    log = logging.getLogger("")
    log.setLevel(logging.DEBUG)
    hdlr = logging.handlers.SMTPHandler(MAILHOST, FROM, TO, SUBJECT)
    hdlr.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))
    log.addHandler(hdlr)
    log.info("Test email contents")
    log.removeHandler(hdlr)

if __name__ == "__main__":
    main()
¿Fue útil?

Solución

I needed to do the exact same thing. You can give smtplib a try. Something like

import smtplib
from email.mime.text import MIMEText

msg = MIMEText('YOUR_MESSAGE_BODY')
me = 'YOUR_SOURCE@EMAIL.COM'
you = 'YOUR_TARGET@EMAIL.COM'
msg['Subject'] = 'YOUR_MESSAGE_SUBJECT'
msg['From'] = me
msg['To'] = you
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

No password is involved.

If you encounter errors like

...    
error: [Errno 61] Connection refused

It probably means you don't have smtp server installed or enabled on your mac, installing postfix (say from macports) should fix that.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top