Javier
Javier

Reputation: 2838

Python2.6 email.parser.parsestr not working?

The function below is giving me trouble for no reason. But I cant find the bug. The problem is that in the function parsestr(), when I put as an argument a literal string like "Hello world!", sends a email with that string. But, and here is the surprise, if I put the variable body, which is also a string, the email has a empty body. I'm using python2.6, and .self.parser is a email.parser.Parser() object.

Thanks!

def send_mail(self, subject, body):

        print "Sending mail",subject
        s = smtplib.SMTP()
        s.connect(myserver, myport)
        s.login(myuser,mypasswd)
        s.starttls()
        s.ehlo_or_helo_if_needed()
        msg = self.parser.parsestr(body) 
        print msg.as_string()

        msg["From"] = self.me
        msg["To"] = self.you
        msg["Subject"] = subject
        msg["orig-date"] = email.utils.formatdate()
        msg["Date"] = email.utils.formatdate()
        log.debug("Sending email")
        s.sendmail(self.me, [self.you], msg.as_string())

Here is the function calling send_mail. It is trivial:

def check_error_directory(self, directory):
    """
        Send an email if some file of the error_directory is not 0
    """

    if(not os.path.exists(directory)):
        log.warning("notify_error_files: The directory %s does not exist",directory)
    else:
        filesize = 0
        body = "Directory: %s\n" % directory
        problem = False
        for fn in os.listdir(directory):
            fnc = os.path.join(directory, fn)
            filesize = os.path.getsize(fnc)
            if(filesize != 0):
                body += "%s: size %s\n" % (fn, filesize)
                problem = True
        if(problem):
            subject = "Possible error in %s" % (directory)
            self.send_mail(subject, body)

Upvotes: 2

Views: 473

Answers (1)

Scott A
Scott A

Reputation: 7834

parsestr is expecting the headers as well as the body.

Try this instead:

from email.mime.text import MIMEText

msg = MIMEText('<html><head><meta http-equiv="Content-Type" content="text/html; CHARSET=UTF-8"></head><body><tt><pre>'
               + body
               + '</pre></tt></body></html>', "html")

Upvotes: 2

Related Questions