Python电子邮件MIME附件文件名 [英] Python email MIME attachment filename

查看:538
本文介绍了Python电子邮件MIME附件文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将CSV文件附加到电子邮件.我可以使用smtplib很好地发送电子邮件,也可以将CSV文件附加到电子邮件中.但是我无法设置附件的名称,因此无法将其设置为.csv.另外,我不知道如何在电子邮件正文中添加短信.

I'm having trouble attaching a CSV file to an email. I can send the email fine using smtplib, and I can attach my CSV file to the email. But I cannot set the name of the attached file, and so I cannot set it to be .csv. Also I can't figure out how to add a text message to the body of the email.

此代码将导致一个名为 AfileName.dat 的附件,而不是所需的 testname.csv 或更好的 attach.csv

This code results in an attachment called AfileName.dat, not the desired testname.csv, or better still 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硬编码为字符串的一部分,并且没有使用相同的命名函数的参数.

In the line part.add_header('Content-Disposition', 'attachment; filename=AFileName') you are hardcoding AFileName as part of the string and are not using the the same named function's argument.

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

To use the argument as the filename change it to

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

在邮件中添加正文

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

这篇关于Python电子邮件MIME附件文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆