0

I am creating a dataframe and trying to send it as attachment, however I get the error message:

TypeError: argument should be a str object or an os.PathLike object returning str, not <class 'bytes'>

df = df[['id','unit_id','receipt']]

    with io.BytesIO() as buffer:
        with pd.ExcelWriter(buffer,engine='xlsxwriter') as writer:
            df.to_excel(writer,sheet_name=str(user.unidad) + ' - ' + str(user.unidad.unidad), index=False)
            writer.save()
            filename = 'Account statement'
            content_type = 'application/vnd.ms-excel'
            # archivo = HttpResponse(buffer.getvalue(), content_type=content_type)
            archivo = bytearray(buffer.getvalue())
            # archivo['Content-Disposition'] = 'attachment; filename="' + filename + '.xlsx"'
    
    subject = 'T500'
    html_message = render_to_string('document_attachment.html')
    plain_message = strip_tags(html_message)
    from_email = 'no-reply@myemail.com'
    to = [user.email]


    msg = EmailMessage(
        subject,
        'Body message.',
        from_email,
        to,
    )
    msg.attach_file(archivo)
    msg.send()

I have tried using archivo.getvalue() or archivo.read() but does not work and have no other idea to get the path of the file.

Any idea?

Adrian
  • 71
  • 5
  • What about saving the dataframe to a file and then passing the path of the file to `attach_file()`? – drum Feb 08 '23 at 03:12
  • That's a good suggestion if I would be working entirely in my local machine, since I am looking to optimize resources I might not want to save it, if I cannot work around it maybe I'll save it, attach it and then delete it, but I am sacrificing executional time while performing. Thanks for the idea. – Adrian Feb 08 '23 at 12:13
  • At the end, I saved it to an objects, attached it and then deleted it... – Adrian Feb 11 '23 at 00:55

0 Answers0