Attach generated CSV file to email and send with Django

前端 未结 3 987
盖世英雄少女心
盖世英雄少女心 2021-02-04 00:54

I need to generate a csv file based on the queryset result, attach the resulting file to an email as attachment and send. As you can see i need to iterate over the assigned_lead

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 00:59

    Python 3 and DictWriter example:

    import csv
    from io import StringIO
    from django.core.mail import EmailMessage
    
    rows = [{'col1': 'value1', 'col2': 'value2'}]
    csvfile = StringIO()
    fieldnames = list(rows[0].keys())
    
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)
    
    email = EmailMessage(
            'Subject',
            'Body',
            'from@email.com',
            ['to@email.com'],
        )
    email.attach('file.csv', csvfile.getvalue(), 'text/csv')
    email.send()
    

提交回复
热议问题