发送循环输出到Python中的电子邮件

问题描述:

仍然是Python世界的新手,所以我首先提出的问题,希望有人可以帮助。 因此,下面是一些简单的代码,列出了路径中的目录,并且我想将输出发送到电子邮件。电子邮件设置的工作原理是它会将“TEXT”发送给我,但我非常努力地试图从打印功能捕获stdout。发送循环输出到Python中的电子邮件

感谢

for root, dirs, files in os.walk(path): 
    for curDir in dirs: 
     fulldir = os.path.join(root, curDir) 
     print '\nThis dir : %s' % (fulldir) 

### Email setup 

SERVER = "myserver" 
PORT = "25" 

FROM = "[email protected]" 
TO = ["[email protected]"] 

SUBJECT = "Some dirs" 

TEXT = "The print loop from above please" 

# Prepare actual message 

message = """\ 
From: %s 
To: %s 
Subject: %s 

%s 
""" % (FROM, ", ".join(TO), SUBJECT, TEXT) 


### Send the message 
server = smtplib.SMTP(SERVER, PORT) 
server.sendmail(FROM, TO, message) 
server.quit() 
+1

不要立即打印目录列表。存储它,例如在列表中,然后您可以打印它并通过电子邮件发送。 – 2014-09-01 10:11:12

+0

Thanks @Duncan - 我之前通过初始化一个列表然后追加fulldir的结果尝试了这一点,但我只有最后一个目录。 – C9000 2014-09-01 10:45:13

+0

请向我们展示您尝试过的代码。也许我们可以帮助解决它。 – 2014-09-01 10:46:36

该代码会加入你用换行的目录列表,确保一个目录,每行上市。

import os 

path = "C:\\tmp" #my test path 

# See http://stackoverflow.com/q/973473/474189 for other alternatives 
dirs = [x[0] for x in os.walk(path) ] 

# Print if needed 
for d in dirs: 
    print "\nThis dir : %s" % (d)   

email_text = "\n".join(dirs)