0

因此,我正在编写一个脚本,该脚本将基于 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 Name\t\tEIN\t\tSub Date\tDays\tAction\n")
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("%s\t%s\t%s\t%d\t%s\n" % (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]))
4

1 回答 1

0

我能够弄清楚我在哪里搞砸了。写完文件后,我忘记了实际关闭文件。我只是将 fp.close() 放在关闭与数据库 con.close() 的连接之后,它通过电子邮件发送文件没有问题。

于 2013-05-31T15:34:49.313 回答