我在将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()
答案 0 :(得分:6)
在行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'))