Search code examples
pythonemailattachmentmime

python MIME: how do i change the name of the attachment?


i can send emails OK using the smtplib functions, but my filename always includes the path of the file:

attachment.add_header("Content-disposition", "attachment", filename=fileToSend)
msg.attach(attachment)

in this case fileToSend = "/home/pi/email/RPSL-0002_2015_11_17__00_00_00.csv"

and the file i receive is homepiemailRPSL-0002_2015_11_17__00_00_00.csv

i have tried substituting fileToSend[11:], and a variable equal to that, but the file path always comes through in the emailed file (without the slashes).

how can i specify the filename of the attachment?


Solution

  • Your use of email.message.Message.add _header is basically correct, except you can't pass in a directory name - if you could control directory structure at the recipient's site, that would be a security problem (as well as a massive usability problem in many scenarios) so it's simply not supported.

    If the value in your variable fileToSend is a user-supplied string which may contain a path, use something like filename=os.path.basename(fileToSend) (see documentation).