I read my data from mongo dB and create a report. I used to save the report as a .xlsx file on my local machine and manually send it using email. I would like to automate this process.
I found a way in Python 3 to save the file in-memory using Python's io.BytesIO() functionality. I tried a few things that I found on stack overflow but it didn't work for me. I would like to get some suggestions on how I can automate my work.
Following is what I have tried,
df = pd.dataframe(df) # has my reports dataframe
def export_excel(df):
with io.BytesIO() as buffer:
writer = pd.ExcelWriter(buffer)
df.to_excel(writer)
writer.save()
return buffer.getvalue()
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
SEND_FROM = 'myemail@company.com'
EXPORTERS = {'dataframe.csv': export_csv, 'dataframe.xlsx': export_excel}
def send_dataframe(send_to, subject, body, df):
multipart = MIMEMultipart()
multipart['From'] = SEND_FROM
multipart['To'] = 'myemail@company.com'
multipart['Subject'] = subject
for filename in EXPORTERS:
attachment = MIMEApplication(EXPORTERS[filename](df))
attachment['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
multipart.attach(attachment)
multipart.attach(MIMEText(body, 'html'))
s = smtplib.SMTP('localhost')
s.sendmail(SEND_FROM, send_to, multipart.as_string())
s.quit()
I do not get an error but don't get an email with an excel attachment too.