Python2.6 email.parser.parsestr 不工作?
下面的函数无缘无故地给我带来了麻烦。但我找不到错误。问题是,在函数 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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
parsestr 需要标头和正文。
试试这个:
parsestr is expecting the headers as well as the body.
Try this instead: