Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python将循环输出发送到电子邮件_Python_Email - Fatal编程技术网

用Python将循环输出发送到电子邮件

用Python将循环输出发送到电子邮件,python,email,Python,Email,仍然是Python领域的新手,所以我的第一个问题是,希望有人能帮助我。 下面是一些简单的代码,列出了路径中的目录,我想将输出发送到电子邮件。电子邮件设置的工作原理是将“文本”发送给我,但我一直在努力从打印功能捕获标准输出 谢谢 for root, dirs, files in os.walk(path): for curDir in dirs: fulldir = os.path.join(root, curDir) print '\nThis dir :

仍然是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 = "me@me.com"
TO = ["me@me.com"]

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

此代码将用换行符连接目录列表,确保每行上列出一个目录

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)

不要立即打印目录列表。将其存储在列表中,然后您可以打印并通过电子邮件发送。谢谢@Duncan-我之前尝试过初始化列表,然后添加fulldir的结果,但我只得到了最后一个目录。请向我们展示您尝试的代码。也许我们可以帮你解决这个问题。道歉@Duncan-在我结束评论之前就发布了。代码是简单的mailDirs=[]在fulldir之前,然后在fulldir mailDirs.append(fulldir)之后,您需要在所有for循环之外声明该列表,否则每次都会覆盖它。也就是说,它将是示例代码中的第一行。