Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python email MIME attachment filename

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()
like image 746
JohnS Avatar asked Mar 24 '15 17:03

JohnS


People also ask

What is mime in Python email?

Today's most common type of email is the MIME (Multipurpose Internet Mail Extensions) Multipart email, combining HTML and plain-text. MIME messages are handled by Python's email.

What is Mimetext?

Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of email messages to support text in character sets other than ASCII, as well as attachments of audio, video, images, and application programs.


1 Answers

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'))
like image 151
halex Avatar answered Sep 28 '22 00:09

halex