Python2.6 email.parser.parsestr不工作?

时间:2011-10-21 18:46:05

标签: python parsing email

以下功能无缘无故给我带来麻烦。但我找不到这个错误。问题是在函数parsestr()中,当我把一个像“Hello world!”这样的文字字符串作为参数时,发送一个包含该字符串的电子邮件。但是,这是一个惊喜,如果我把变量 body (也是一个字符串),电子邮件有一个空体。我正在使用python2.6,而.self.parser是一个email.parser.Parser()对象。

谢谢!

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())

这是调用send_mail的函数。这是微不足道的:

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)

1 个答案:

答案 0 :(得分:2)

parsestr期待标题和正文。

请改为尝试:

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")