将CSV文件作为单个电子邮件附件发送

时间:2015-09-24 10:35:54

标签: python email csv email-attachments

有一个脚本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()

脚本运行没有错误,但没有发送电子邮件

1 个答案:

答案 0 :(得分:1)

您错过了登录部分。你应该在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

用以下代码替换循环。

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)