0

I am trying to send .csv file generated from dictionary using smtplib and MIME. I am able to send correct data to mail, but for some reason the data is always extended as .htm when downloaded from the mail itself. So my question is - how to set the MIME correctly, so the data is always in .csv data type. Here is my code as of now:

def new_email(df):
    message = MIMEMultipart()
    message['Subject'] = "New data"
    message['From'] = "someGenericMail@outlook.com"
    message['To'] = "someOthergGenericMail@gmail.com"

    bio = io.BytesIO()
    df.to_csv(bio,mode="wb")
    bio.seek(0)
    attachement = MIMEApplication(bio.read(),"csv")
    bio.close()
    attachement.add_header("Content-Disposition", "attachement", filename="Results.csv")

    body = MIMEText("Here is your data", 'plain')
    message.attach(body)
    message.attach(attachement)
    with smtplib.SMTP("smtp.office365.com", 587) as server:
        server.starttls()
        server.login("someGenericMail@outlook.com","password")
        server.sendmail("someGenericMail@outlook.com","someOthergGenericMail@gmail.com", message.as_string())

This is what I get when I download attachement from the recieved mail: enter image description here

1 Answers1

0

It is "text/csv" and there is a complete list of MIME types here: https://docs.w3cub.com/http/basics_of_http/mime_types/complete_list_of_mime_types.html

d r
  • 3,848
  • 2
  • 4
  • 15
  • Hi, thanks for the comment. Where exactly should this "text/csv" be added? When used as attachement = MIMEApplication(bio.read(),"text/csv") I am still getting the .htm extenstion. – Haggerman Swaggerman Jun 26 '22 at 09:40
  • I'd say here --> body = MIMEText("Here is your data", 'plain') --> try 'text/csv' instead of 'plain' but I should get deeper into the code to check the rest. Hoppefully it will help you. If that is the case I'm gled to be heree for you. You can also check some other codes for this purpose like this one: --> https://stackoverflow.com/questions/3362600/how-to-send-email-attachments OR this one --> https://www.tutorialspoint.com/send-mail-with-attachment-from-your-gmail-account-using-python – d r Jun 26 '22 at 10:27
  • Here is everything you need --> https://realpython.com/python-send-email/#adding-attachments-using-the-email-package – d r Jun 26 '22 at 10:36