有一个脚本test.py,它将生成2到3个csv文件进行sql查询。CSV文件将生成并保存在与test.py相同的路径中。生成csv文件是正确的,但电子邮件附件不工作下面是我的代码片段:
import smtplib
import csv
from email.mime.multipart import MIMEMultipart
from email.message import Message
from email.mime.text import MIMEText
with open('record1.csv', 'wb') as f:
fieldnames = ['Name','No audits']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for data in query:
writer.writerow({'Name' : data[0], 'No audits': data[1]})
## below code as problem
#Mail format
COMMASPACE = ', '
SERVER = "localhost"
msg = MIMEMultipart()
msg['Subject'] = 'Audit records'
emailfrom = "xyz" // Giving proper outlook mail id
emailto = ['abc'] // // Giving proper outlook mail id lists
msg['From'] = emailfrom
msg['To'] = COMMASPACE.join(emailto)
msg.preamble = 'List of audit records '
csvfiles = ['record1.csv', 'record2.csv']
for csv in csvfiles:
print csv
with open(csv) as fp:
record = MIMEText(fp.read())
msg.attach(record)
print "INFO: "
server = smtplib.SMTP(SERVER)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()
脚本运行没有错误,但没有发送电子邮件
您错过了登录部分。您应该在smtplib.SMTP()中提供适当的服务器和端口。
将最后3行改为以下内容。下面的代码是gmail,根据outlook更新代码。
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(emailfrom, 'password')
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()
编辑:进口:
from email import encoders
from email.mime.base import MIMEBase
import os
并将loop替换为以下代码:
for csv in csvfiles:
print csv
with open(csv) as fp:
record = MIMEBase('application', 'octet-stream')
record.set_payload(fp.read())
encoders.encode_base64(record)
record.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(csv))
msg.attach(record)