Python email MIME attachment filename

JohnS picture JohnS · Mar 24, 2015 · Viewed 10k times · Source

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'] = "[email protected]"
    msg['To'] =  "[email protected]"
    #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("[email protected]","password")
    server.sendmail("[email protected]", "[email protected]", msg.as_string())

if __name__=="__main__":
main()

Answer

halex picture halex · Mar 24, 2015

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