【发布时间】:2014-08-20 03:49:49
【问题描述】:
我正在删除几个 30 天前的文件夹,并希望使用 gmail 将所有已删除文件夹的列表邮寄给自己。
目前它可以毫无问题地删除文件夹,但电子邮件中的消息和主题都是空白的。我错过了什么?
import os
import time
import shutil
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import encoders
sender = "my_email@gmail.com"
receivers = ["my_email@gmail.com"]
username = 'my_email'
password = 'passwd'
numdays = 86400*30
now = time.time()
directory=os.path.join("/home","/Downloads/trial/")
for r,d,f in os.walk(directory):
for dir in d:
timestamp = os.path.getmtime(os.path.join(r,dir))
if now-numdays > timestamp:
try:
print "removing ",os.path.join(r,dir)
shutil.rmtree(os.path.join(r,dir))
except Exception,e:
print e
pass
else:
print "Deleted folders are: %s" % os.path.join(r,dir)
msg = MIMEMultipart()
msg['To'] = 'my_email@gmail.com'
subject = "Deleted Folders : %s" % os.path.join(r,dir)
msg['Subject'] = subject
try:
mailserver = smtplib.SMTP("smtp.gmail.com", 587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login(sender, password)
mailserver.sendmail(sender, to, msg.as_string())
mailserver.close()
print "Successfully Sent email"
except smtplib.SMTPException:
print"Error: Unable to send email"
我收到的电子邮件主题为:已删除文件夹:/home/Downloads/trial/4/4
我的目标是创建电子邮件的消息/内容/正文,并删除所有文件夹。我在标准输出中看到了我想要的输出,即
removing /home/Downloads/trial/1
Deleted folders are: /home/Downloads/trial/1
removing /home/Downloads/trial/2
Deleted folders are: /home/Downloads/trial/2
removing /home/Downloads/trial/3
Deleted folders are: /home/Downloads/trial/3
【问题讨论】:
-
你的缩进有点乱
标签: python email smtp mime shutil