Attach generated CSV file to email and send with Django

前端 未结 3 985
盖世英雄少女心
盖世英雄少女心 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 01:15

    Is there a particular reason you're using an additional function at all? Just build your csv in memory - you can't avoid that if you're attaching it to email - and send that.

    assigned_leads = lead.objects.filter(assigned_to__in=usercompany).distinct()
    csvfile = StringIO.StringIO()
    csvwriter = csv.writer(csvfile)
    for leads in assigned_leads:
        csvwriter.writerow([leads.business_name, leads.first_name, leads.last_name, leads.email, leads.phone_number,leads.address, leads.city, leads.state, leads.zipcode, leads.submission_date, leads.time_frame, leads.comments])
    message = EmailMessage("Hello","Your Leads","myemail@gmail.com",["myemail@gmail.com"])
    message.attach('invoice.csv', csvfile.getvalue(), 'text/csv')
    

提交回复
热议问题