Home > Net >  Send csv files with data from db to email python
Send csv files with data from db to email python

Time:01-10

I have db and there is table called Users.

id name last_name status
1 John Black active
2 Drake Bell disabled
3 Pep Guardiola active
4 Steve Salt disabled

I would like to send to one email two csv files. The first one will be with name sucess.csv and there will be ID from the table, with status active, and the second one csv will be named failed.csv and inside will be ID with status disabled. Right now my code looks like this:

def send_user_report():
    logger.info('User report generating')

    user_data = {}
    user = Users.objects.values('id', 'status')

    buffer = io.StringIO()
    writer = csv.writer(buffer)

    writer.writerow([])
    

 
    email = EmailMessage('Users report', body, to=settings.EMAIL_TEST)
    email.attach('sucess_report.csv', buffer.getvalue(), 'text/csv')
    email.send()

CodePudding user response:

Write to two attachments:

def send_user_report():
    logger.info('User report generating')

    user_data = {}
    user = Users.objects.values('id', 'status')

    buffer = io.StringIO()
    writer = csv.writer(buffer)
    for user in Users.objects.filter(status='active')
        writer.writerow([user.pk])
    
    buffer2 = io.StringIO()
    writer2 = csv.writer(buffer2)
    for user in Users.objects.filter(status='disabled')
        writer2.writerow([user.pk])
    
    email = EmailMessage('Users report', '', to=settings.EMAIL_TEST)
    email.attach('sucess_report.csv', buffer.getvalue(), 'text/csv')
    email.attach('failed_report.csv', buffer2.getvalue(), 'text/csv')
    email.send()
  •  Tags:  
  • Related