使用Python 2.7通过电子邮件发送文本附件几乎正常工作

时间:2013-05-30 19:21:57

标签: email python-2.7 gmail text-files email-attachments

所以我正在编写一个脚本,它将生成一个基于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]))

1 个答案:

答案 0 :(得分:0)

我能弄清楚我搞砸了哪里。一旦写完文件,我就忘了真正关闭文件了。我只是将fp.close()放在我关闭数据库con.close()的连接之后,它发送文件没问题。