Python 电子邮件 MIME 附件文件名

Python email MIME attachment filename

我在将 CSV 文件附加到电子邮件时遇到问题。我可以使用 smtplib 正常发送电子邮件,并且可以将我的 CSV 文件附加到电子邮件中。但是我不能设置附件的名称,所以不能设置为.csv。我也不知道如何在电子邮件正文中添加短信。

此代码生成名为 AfileName.dat 的附件,而不是所需的 testname.csv,或者更好attach.csv

#!/usr/bin/env python

import smtplib
from email.mime.multipart import MIMEMultipart
from email import Encoders
from email.MIMEBase import MIMEBase

def main():
    print"Test run started"
    sendattach("Test Email","attach.csv", "testname.csv")
    print "Test run finished"

def sendattach(Subject,AttachFile, AFileName):
    msg = MIMEMultipart()
    msg['Subject'] = Subject 
    msg['From'] = "from@email.com"
    msg['To'] =  "to@email.com"
    #msg['Text'] = "Here is the latest data"

    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(AttachFile, "rb").read())
    Encoders.encode_base64(part)

    part.add_header('Content-Disposition', 'attachment; filename=AFileName')

    msg.attach(part)

    server = smtplib.SMTP("smtp.com",XXX)
    server.login("from@email.com","password")
    server.sendmail("email@email.com", "anotheremail@email.com", msg.as_string())

if __name__=="__main__":
main()

在行 part.add_header('Content-Disposition', 'attachment; filename=AFileName') 中,您将 AFileName 硬编码为字符串的一部分,并且没有使用相同命名函数的参数。

要将参数用作文件名,请将其更改为

part.add_header('Content-Disposition', 'attachment', filename=AFileName)

向您的电子邮件添加正文

from email.mime.text import MIMEText
msg.attach(MIMEText('here goes your body text', 'plain'))