将生成的CSV文件附加到电子邮件并使用Django发送

时间:2013-07-11 03:25:23

标签: python django

我需要根据查询集结果生成一个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('/')

3 个答案:

答案 0 :(得分:30)

您是否有特殊原因要使用其他功能?只需在内存中构建你的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')

答案 1 :(得分:1)

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()
for row in rows:
     writer.writerow(row)

email = EmailMessage(
        'Subject',
        'Body',
        'from@email.com',
        ['to@email.com'],
    )
email.attach('file.csv', csvfile.getvalue(), 'text/csv')
email.send()

答案 2 :(得分:-1)

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