简体   繁体   English

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

[英]Python - Sending email with CSV attachment

I have a script that creates a CSV file to later use to send in an email. 我有一个脚本,该脚本创建了一个CSV文件,以后可以用来发送电子邮件。 I am running into issues opening the file as read-only to then send as an attachment. 我遇到了以只读方式打开文件然后以附件形式发送的问题。 Below is my current code. 下面是我当前的代码。

#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)

I am not getting any error messages but the code dies when trying to open the CSV file within the createEmail function "with open(outputFile, newline='') as file:" . 我没有收到任何错误消息,但是尝试在createEmail函数“以open(outputFile,newline ='')作为文件:”中打开CSV文件时,代码消失了。

It ended up that instead of calling outputFile in the "read" statement, I needed to call the file name itself. 最终,我需要调用文件名本身,而不是在“ read”语句中调用outputFile。

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

changed to: 变成:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM