问题
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.
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()
回答1:
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)
To add a body to your email
from email.mime.text import MIMEText
msg.attach(MIMEText('here goes your body text', 'plain'))
来源:https://stackoverflow.com/questions/29239572/python-email-mime-attachment-filename