我对python编程很陌生,请放轻松!
我正在查询我的 MySQL 数据库并将输出写入文件并发送结果的电子邮件。但是,电子邮件是在写入文件之前发送的。在发送电子邮件之前,如何告诉我的代码进行查询并写入文件?
#!/usr/bin/python
# Import smtplib for the actual sending function
import smtplib
import MySQLdb as mdb
import sys
import csv
con = mdb.connect('localhost', 'myuser', 'mypassword', 'mydatabase');
with con:
cur = con.cursor()
cur.execute("SELECT * from vw_mail")
rows = cur.fetchall()
c = csv.writer(open('/home/pi/mail.csv','wb'))
c.writerows(rows)
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open('/home/pi/mail.csv','rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'MySubject'
msg['From'] = 'me@me.com'
msg['To'] = 'you@you.com'
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('smtp.me.com')
s.sendmail('me@me.com','you@you.com', msg.as_string())
s.quit()