0

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()

TLanni
  • 330
  • 1
  • 4
  • 15

1 Answers1

0

File contents are always bytes, no matter which file type you are talking about. Programs may hide that fact from you, but it's still true.

When you write "it's in the byte format so it's unreadable", I assume you mean that your email client does not help you to view the file in the way you expected. To help your email client do that, try setting the content_type attribute of FileAttachment to something that matches the file type of your attachment. See Response Content type as CSV for suggested values.

Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63