用python发送电子邮件,消息丢失
Posted
技术标签:
【中文标题】用python发送电子邮件,消息丢失【英文标题】:Sending email in python, message missing 【发布时间】: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
【问题讨论】:
你的缩进有点乱 【参考方案1】:试试这个:
deleted_folders = []
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:
shutil.rmtree(os.path.join(r,dir))
deleted_folders.append("Deleted folders are: %s" %
os.path.join(r,dir))
# Bad, it's almost never appropriate to catch all Exceptions
# In this case, OSError seems better
except Exception,e:
pass
body = MIMEText("\n".join(deleted_folders), "plain")
msg.attach(body)
【讨论】:
谢谢伊恩。是的,这会打印出在主题中删除的文件夹。有没有办法在电子邮件的内容中得到相同的内容。 抱歉错过了,现在?以上是关于用python发送电子邮件,消息丢失的主要内容,如果未能解决你的问题,请参考以下文章