0

I am able to send emails with attachments such as images but unable to do so with csv files. I am pretty new to Python and unsure what to do next.

import os  
from email.mime.multipart import MIMEMultipart    
from email.mime.text import MIMEText  
from email.mime.application import MIMEApplication  
import smtplib  

email_address = os_environ.get(`EMAIL_ADDRESS`)  
email_password = os.environ.get(`EMAIL_PASS`)  

message = MIMEMultipart()  
message['From'] = email_address  
message['To'] = #Sending message to my email  
message['Subject'] = `This is A Test Email`  
message.attach(MIMEText('body'))  

file_name = 'Daily_Ticket_Aging_Overview' 

with open('C:/Users\\odigii01\\Desktop\\Daily_Ticket_Aging_Overview.csv', 'rb') as file:  
    message.attach(MIMEApplication(file.read(), Name = file_name))  

with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:  
    smtp.ehlo() #Telling the client that we want to send an email  
    smtp.starttls() #TLS MODE (Transport Layer Security)  
    smtp.login(email_address, email_password)  
    smtp.send_message(message)  
    print('Sent...')  

Realized the data is being pulled but not as a CSV File. I can download the data and open it in the Notepad.

Iyoodigie
  • 1
  • 1
  • You probably need to specify the mime type of the attachment as text/csv so that the receiving mail client knows what to do with it. – Robert Jan 31 '23 at 16:02
  • As an aside, it looks like your `email` code was written for an older Python version. The `email` module in the standard library was overhauled in Python 3.6 to be more logical, versatile, and succinct; new code should target the (no longer very) new `EmailMessage` API. Probably throw away this code and start over with modern code from [the Python `email` examples documentation.](https://docs.python.org/3/library/email.examples.html) Modern code should basically not use the legacy `MIMEMultipart` etc classses. – tripleee Jan 31 '23 at 17:26
  • You are not passing in a file name or file type, so it basically gets attached as untyped data. You want `filename="something.csv"` for Windows, and `Content-type: text/csv` for real computers. – tripleee Jan 31 '23 at 17:28
  • Completely missed that...thank you! Definitely will look into starting over with modern code, it's a start for now. – Iyoodigie Jan 31 '23 at 17:48

0 Answers0