【问题标题】:Python email MIME attachment filenamePython 电子邮件 MIME 附件文件名
【发布时间】:2015-05-28 04:10:25
【问题描述】:

我在将 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()

【问题讨论】:

    标签: python-2.7 csv mime email-attachments


    【解决方案1】:

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

    【讨论】:

    • 我的补充问题是 - 如何在电子邮件正文中添加一些文本?我试过 msg['Text'] = "Here is the latest data",但什么也没发生
    • 对我来说,扩展导致了一个问题。附件以attachment1 发送。于是我改成了filename = name + '.pdf'
    猜你喜欢
    • 2021-08-19
    • 2013-07-22
    • 2017-11-07
    • 2015-02-10
    • 1970-01-01
    • 2014-08-30
    • 2015-07-09
    • 1970-01-01
    • 2013-03-18
    相关资源
    最近更新 更多