25

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

<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('/')
4

3 回答 3

44

您使用附加功能是否有特殊原因?只需在内存中构建您的 csv - 如果您将其附加到电子邮件中,您将无法避免这种情况 - 并将其发送。

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')
于 2013-07-11T03:29:58.353 回答
7

Python 3 和DictWriter示例:

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()
于 2016-11-18T16:40:53.343 回答
-2
Neither are working :(

Approach 1:
        msg = EmailMultiAlternatives(subject, body, from_email, [to])
        msg.attach_alternative(file_content, "text/html")
        msg.content_subtype = 'html'
        msg.send()

Approach 2: 
        # email = EmailMessage(
        #     'Report Subject',
        #     "body",
        #     'xx@yy.com',
        #     ['zz@uu.com'],
        #     connection=connection,
        # )
        # email.attach('Report.html', body, 'text/html')
        # email.send()
于 2017-05-24T11:20:25.917 回答