How to send pdf as an email attachment in Django


December 2018


4.8k time


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

                messages.success(request,'Please check your email id '+email+' for further instructions.')  
                return HttpResponse('success')         
            #           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):
   = "\""+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
        return None

1 answers


Вы не должны использовать django.core.files.ContentFile, он принимает только строку.

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