将生成的CSV文件附加到电子邮件并使用Django发送 [英] Attach generated CSV file to email and send with Django

查看:70
本文介绍了将生成的CSV文件附加到电子邮件并使用Django发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要基于queryset结果生成一个csv文件,将结果文件作为附件附加到电子邮件中并发送。如您所见,我需要遍历assigned_leads并将其写入文件,因此我认为yield可以解决问题。现在,当我运行代码时,我收到带有以下消息而不是我期望的行的带有附件的电子邮件。如果我使用return,则会从queryset结果中获得一行。

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_leads and write it to a file so i thought yield would do the trick. Now when i run the code i receive the email with attachment with below message instead of the rows i expect. If i use return i get the one row from the queryset result.

<generator object data at 0x7f5e508d93c0>

def send_lead_reminder(request):
    usercompany = Listing.objects.filter(submitted_by=request.user)
    assigned_leads = lead.objects.filter(assigned_to__in=usercompany).distinct() 
    def data():
        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])
             yield csvfile.getvalue()
    message = EmailMessage("Hello","Your Leads","myemail@gmail.com",["myemail@gmail.com"])
    message.attach('invoice.csv', data(), 'text/csv')
    #message.to="myemail@gmail.com"
    message.send()
    return HttpResponseRedirect('/')


推荐答案

是否存在特定原因您正在使用根本没有其他功能?只需在内存中建立csv-如果将其附加到电子邮件中就无法避免-然后发送。

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')

这篇关于将生成的CSV文件附加到电子邮件并使用Django发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆