所以我正在编写一个脚本,该脚本将生成一个基于MYSQL数据库的文本文件和电子邮件文件作为附件通过gmail。我几乎得到了一切工作,但它所附加的文件,而正确命名,显示为空白。我查阅了文档并提出了许多问题(这就是我如何能够做到的),但我无法确定我的具体错误在哪里。我很确定这是显而易见的,但在过去7个小时的工作后,我看不出来。我对编程并不陌生,但我对python和以编程方式处理电子邮件都很陌生,所以这可能也是问题的一部分。不管怎样,这是有问题的文件。非常感谢任何帮助。顺便说一句,我想感谢这里的所有人,感谢他们在我制作Android应用时给予我的帮助。我能够让所有内容正常运行并将其发布到商店中。=)
(我在这里编辑了数据库登录和电子邮件登录的凭据为假值)
import MySQLdb as mdb
import sys, time, datetime
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
try:
# prompt = ('> ')
t = time.localtime()
fp = file('bus_rep_%s-%s-%s--%s.%s.%s.txt' % (t[0], t[1], t[2], t[3], t[4], t[5]), 'a+')
fp.write("Business NamettEINttSub DatetDaystActionn")
con = mdb.connect('XXX.XXX.XXX.XXX', 'USERNAME', 'USERPASS', 'DBNAME');
# print "Enter start date: YYYY-MM-DD"
start_date = 2000-01-01
cur = con.cursor()
current_date = datetime.date.today()
# print "Current Date = %r" % current_date
cur.execute('SELECT BusName, EIN, DWHDateSubmitted FROM Business WHERE DWHSubmitted LIKE %d AND DWHDateSubmitted IS NOT NULL' % (1))
# Fetch all the rows in a list of lists.
results = cur.fetchall()
for row in results:
bname = row[0]
ein = row[1]
subdate = row[2]
# print bname
# print ein
# print subdate
days_passed = current_date - subdate
days_passed = days_passed.days
# print "days_passed = %r" % days_passed
if days_passed > 30:
action = 'Contact Claims'
else:
action = ' '
# print "bname = %s, EIN = %s, subdate = %s, days_passed = %d, action = %s" % (bname, ein, subdate, days_passed, action )
fp.write("%st%st%st%dt%sn" % (bname, ein, subdate, days_passed, action ))
except mdb.Error, e:
print "Error: %d: %s" % (e.args[0],e.arge[1])
sys.exit(1)
con.close()
gmail_user = "USER@GMAIL.com"
gmail_pwd = "GMAILPASS"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'r').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
mailServer.close()
mail("email@fakesite.com",
"Daily Business Claim Submission Report",
"Attached is the automatically generated Daily Business Claim Report.",
"bus_rep_%s-%s-%s--%s.%s.%s.txt" % (t[0], t[1], t[2], t[3], t[4], t[5]))
我知道我在哪里搞砸了。我忘记在写完文件后关闭它。我只是把fp.close()放在我关闭连接到数据库的地方之后con.close(),它通过电子邮件发送文件没有问题。