Reputation: 83
for my homework, I need to send an attach pdf to e-mail.I have when I download I have format error: not a pdf or damaged.
Definition of render_to_pdf
utils.py
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
the generated function :
views.py
class GeneratePDF(View):
context_object_name = 'services'
template_name = 'pdf.html'
def get(self, request, *args, **kwargs):
template = get_template('configuration/pdf.html')
f=Reservation.objects.all().filter(Q(valide=True, option__in=Option.objects.all().filter(Q(code_option='GTR',
posseder_niveau__in=Posseder_Niveau.objects.all().filter(niveau_id = 1))))).order_by('date_du_jour_reserve')
c = Plage_Horaire.objects.all()
context = {
"c":c,
'f':f,
}
html= template.render(context)
pdf = render_to_pdf('configuration/pdf.html', context)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = "emploidetemps.pdf"
content = "inline; filename=%s " %filename
download = request.GET.get("download")
if download:
content = "attachment; filename=%s" %(filename)
response['Content-Disposition'] = content
return response
return HttpResponse("Not found")
Email function
def mailjoin(request):
GeneratePDF.as_view()
email = EmailMessage()
email.subject = "test"
email.body='emploi de temps'
email.from_email = settings.EMAIL_HOST_USER
email.to = ['[email protected]' ]
email.attach("emploidetemps.pdf", 'application/pdf')
email.send()
Upvotes: 0
Views: 1639
Reputation: 9117
Yes, you can send email with an attachment without saving it in database, see Django EmailMessage.attach()
description. To send a PDF as an attachement simply add it to an email (as stated in similar SO questions):
mail.attach('my_pdf_filename.pdf', my_pdf.read(), 'application/pdf')
Upvotes: 2