Python电子邮件MIME附件文件名

Joh*_*hnS 4 csv mime email-attachments python-2.7

我在将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()
Run Code Online (Sandbox Code Playgroud)

hal*_*lex 6

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

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

part.add_header('Content-Disposition', 'attachment', filename=AFileName)
Run Code Online (Sandbox Code Playgroud)

在邮件中添加正文

from email.mime.text import MIMEText
msg.attach(MIMEText('here goes your body text', 'plain'))
Run Code Online (Sandbox Code Playgroud)