如何发送pdf作为电子邮件附件在Django [英] How to send pdf as an email attachment in Django

查看:184
本文介绍了如何发送pdf作为电子邮件附件在Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下两个功能,通过邮件即时创建和发送pdf。我究竟做错了什么。 (导出pdf函数在浏览器中显示时正常工作。)



我遇到的错误是TypeError:'ContentFile'对象不支持索引即可。我做错了什么?几乎所有这些代码都是从一些博客中获取的,所以我不知道它是如何工作的。但如果你不明白一些事情请评论。我会回复

  if request.method ==POST:

form = ReportSendMailForm(request.POST)

如果form.is_valid():

email = form.cleaned_data ['mail']
message = form.cleaned_data ['message']
打印电子邮件
打印消息
result = export_pdf(request,id)
file_to_be_sent = ContentFile(result)
#print file_to_be_sent
if result:
#尝试:

subject,from_email,to = request.user.username +'发送了一份报告供审核','Dtz Team',电子邮件
html_content = render_to_string('email / report.html ',{'username':request.user,'messgae':message})
msg = EmailMultiAlternatives(subject,'',from_email,[to])

msg.attach_alternative(html_content ,text / html)
msg.at tach(Report.pdf,file_to_be_sent,application / pdf)

msg.send()
messages.success(请检查您的电子邮件ID'+ email +'
return HttpResponse('success')
#except:
#pass
messages.error(请求,'在pdf中出现错误')
return HttpResponse(status = 410)



导出PDF功能



  def export_pdf(request,id):
report = Report.objects.get(id = id)
options1 = ReportPropertyOption.objects.filter (report = report,is_active = True)
在option1中的选项:
option.exterior_images = ReportExteriorImages.objects.filter(report = option)
option.interior_images = ReportInteriorImages.objects.filter report = option)
option.floorplan_images = ReportFloorPlanImage s.objects.filter(report = option)
option.fitouts = ReportFitOut.objects.filter(propertyoption = option)
if(option.gps_longitude):
option.map =http: //maps.google.com/maps/api/staticmap?zoom=12&size=400x400&maptype=roadmap&sensor=false&center=\ + STR(option.gps_latidtude)+ + STR( option.gps_longitude)+\

html = render_to_string('report / export.html',{'pagesize':'A4',},context_instance = RequestContext(request,{'options1 ':options1,'meta':report.meta}))
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode(UTF-8)) ,dest = result,link_callback = fetch_resources)
如果不是pdf.err:
返回结果
else:
返回无
pre>

解决方案

您不应该使用 django.core.files.ContentFile ,它只接受字符串。

  file_to_be_sent = export_pdf(request,id).getvalue()#如果不是无
msg.attach Report.pdf,file_to_be_sent,application / pdf)


Hi I am using the follwoing 2 functions to create and send a pdf via mail on the fly. What Am I doing wrong. (The export pdf function works properly when showing it in the browser.)

The error I am getting is "TypeError: 'ContentFile' object does not support indexing". What I am doing wrong? Almost all of this code has been taken from some blogs, so I dont know how it exactly works. But if you dont understand some things please comment. I will reply.

 if request.method=="POST":

    form = ReportSendMailForm(request.POST)

    if form.is_valid():

        email = form.cleaned_data['mail']
        message = form.cleaned_data['message']             
        print email
        print message
        result = export_pdf(request,id)
        file_to_be_sent= ContentFile(result)
        #print file_to_be_sent
        if result:
            #try :

                subject, from_email, to =  request.user.username+' has sent a report for review',' Dtz Team', email                   
                html_content = render_to_string('email/report.html',{'username':request.user,'messgae':message})                         
                msg = EmailMultiAlternatives(subject,'', from_email, [to])

                msg.attach_alternative(html_content, "text/html")
                msg.attach("Report.pdf", file_to_be_sent, "application/pdf")

                msg.send()  
                messages.success(request,'Please check your email id '+email+' for further instructions.')  
                return HttpResponse('success')         
            #except:
            #           pass             
messages.error(request,'Error occured in the pdf.')            
return HttpResponse(status=410)  

Export PDF function

def export_pdf(request,id):
    report = Report.objects.get(id=id)                
    options1 = ReportPropertyOption.objects.filter(report=report,is_active=True)
    for option in options1:
        option.exterior_images = ReportExteriorImages.objects.filter(report = option)  
        option.interior_images = ReportInteriorImages.objects.filter(report = option)
        option.floorplan_images = ReportFloorPlanImages.objects.filter(report = option)
        option.fitouts =    ReportFitOut.objects.filter(propertyoption = option)   
        if (option.gps_longitude):
            option.map = "http://maps.google.com/maps/api/staticmap?zoom=12&size=400x400&maptype=roadmap&sensor=false&center=\""+str(option.gps_latidtude)+","+str(option.gps_longitude)+"\""                 

    html  = render_to_string('report/export.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request,{'options1':options1,'meta':report.meta}))
    result = StringIO.StringIO()       
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources )
    if not pdf.err:
        return result
    else:
        return None

解决方案

You should not use django.core.files.ContentFile, it accepts only strings.

file_to_be_sent= export_pdf(request,id).getvalue() # if it's not None
msg.attach("Report.pdf", file_to_be_sent, "application/pdf")

这篇关于如何发送pdf作为电子邮件附件在Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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