I need to email the pandas dataframe df
as an attachment using exchangelib.
below is my code
import io
attachments=[]
x=io.BytesIO(df.to_records(index=False))
content=x.getvalue()
type(content) #bytes
send_email(account, 'Subject', 'test email', ['testemail.com'],
attachments=attachments)
when i use the above code i get the email with attachment,but it's in the byte format so it's unreadable.
This is because the type(content) is "bytes"
Below code works perfectly fine.
This is because type(content) is "class 'bytes'> "
but i am not allowed to save my dataframe locally as .csv file.
I want send the dataframe directly as an email attachment.
How can I convert my df
in the "class 'bytes'> " format and email the attachment in csv ?
attachments = []
with open('test.csv', 'rb') as f:
content = f.read()
type(content) #<class 'bytes'>
attachments.append(('test.csv', content))
below is send_email i am using
from exchangelib import Configuration, Account, DELEGATE
from exchangelib import Message, Mailbox, FileAttachment
def send_email(account, subject, body, recipients, attachments=None):
"""
Send an email.
Parameters
----------
account : Account object
subject : str
body : str
recipients : list of str
Each str is and email adress
attachments : list of tuples or None
(filename, binary contents)
Examples
--------
"""
to_recipients = []
for recipient in recipients:
to_recipients.append(Mailbox(email_address=recipient))
# Create message
m = Message(account=account,
folder=account.sent,
subject=subject,
body=body,
to_recipients=to_recipients)
# attach files
for attachment_name, attachment_content in attachments or []:
file = FileAttachment(name=attachment_name, content=attachment_content)
m.attach(file)
m.send_and_save()