Python-使用CSV附件发送电子邮件

时间:2019-07-11 23:21:20

标签: python csv email dictionary

我有一个脚本,该脚本创建CSV文件,以便以后用于发送电子邮件。我遇到了以只读方式打开文件然后以附件形式发送的问题。下面是我当前的代码。

#Below code creates the CSV file
keys = lstMaster[0].keys()

with open('myfile.csv' , 'w') as outputFile:
    writer = csv.DictWriter(outputFile, keys)
    writer.writeheader()
    writer.writerows(lstMaster)

def createEmail(outputFile)
    msg = MIMEMultipart()
    msg['Subject'] = 'CSV report'
    msg['From'] = "email@domain.com"
    msg['To'] = (["me@domain.com"])
    msg.preamble = 'Attachment' 

    with open(outputFile, newline='') as file:
        attachment = csv.DictReader(file)

    attachment.add_header('Content-Disposition', 'attachment', `enter code here`filename='myfile.csv')
    msg.attach(attachment)

我没有收到任何错误消息,但是尝试在createEmail函数“使用open(outputFile,newline ='')作为文件:”中打开CSV文件时,代码消失了。

1 个答案:

答案 0 :(得分:0)

最终,我需要调用文件名本身,而不是在“ read”语句中调用outputFile。

with open(outputFile, newline='') as file:

更改为:

with open('filename', 'r') as file: