Search code examples
pythonpandassendgridsendgrid-api-v3

How to send email with dataframe as attachment using sendgrid api in python?


Hey i need to send email notification whenever an event happens, i am able to send the email but i am not sure how to attach dataframe as an attachment to it.

def send_mail(content):

    # Defining Email Body and Notificaion type.    
    html_content='Hi Team,</br><strong>{}</br></br>Thanks</strong></br></br>'.format(content)

    # Defining Email_Format.
    message = Mail(
        from_email='[email protected]',
        to_emails=['[email protected]'],
        subject='test',
        html_content=html_content)
    
    try:
        sg = SendGridAPIClient(SENDGRID_API_KEY)
        response = sg.send(message)
    except Exception as e:
        logging.error(e.message)
    
    return None

I am able send notification through above code, but i need to attach dataframe as an attachment to that mail, i have no clue how to attach it.

df_to_attach. --- I need to attach this dataframe as an attachment

Id   Name
1    rick
2    John
3    uran
4    Turan

Solution

  • Twilio SendGrid developer evangelist here.

    As Joshua suggested in the comment, convert your dataframe to CSV format and then attach as a CSV file. Something like this:

    from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition, ContentId)
    import base64
    
    def send_mail(content, dataframe):
    
        # Defining Email Body and Notificaion type.    
        html_content='Hi Team,</br><strong>{}</br></br>Thanks</strong></br></br>'.format(content)
    
        # Defining Email_Format.
        message = Mail(
            from_email='[email protected]',
            to_emails=['[email protected]'],
            subject='test',
            html_content=html_content)
      
        base64_csv = base64.b64encode(dataframe.to_csv(index=False).encode())
        message.attachment = Attachment(FileContent(base64_csv),
                                        FileName('dataframe.csv'),
                                        FileType('text/csv'),
                                        Disposition('attachment'),
                                        ContentId('datafrane'))
        
        try:
            sg = SendGridAPIClient(SENDGRID_API_KEY)
            response = sg.send(message)
        except Exception as e:
            logging.error(e.message)
        
        return None