djangoweasyprint

How to send waysiprint pdf by mail


I'm trying to generate a pdf file from an HTML template using Weasyprint python package and I need to send it via email using.

Here's what i have tried:

views.py :

       user_info = {
            "name": 'nadjib',
        }
        html_string = render_to_string('Proformas/command.html')

        html = HTML(string=html_string,base_url=request.build_absolute_uri())
        # html.write_pdf(target='/tmp/mypdf.pdf');

        fs = FileSystemStorage('/tmp')
        with fs.open('mypdf.pdf') as pdf:
          response = HttpResponse(pdf, content_type='application/pdf')
          response['Content-Disposition'] =  'filename="Commande.pdf"'
          pdf = weasyprint.HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf(
              stylesheets=[weasyprint.CSS(string='body { font-family: serif}')])
          to_emails = ['nadjzdz@gmail.com']
          subject = "SH INFOR FACTURE"
          email = EmailMessage(subject, body=pdf, from_email='attaazd@gmail.com', to=to_emails)
          email.attach("Commande".format(user_info['name']) + '.pdf', pdf, "application/pdf")
          email.content_subtype = "pdf"  # Main content is now text/html
          email.encoding = 'us-ascii'
          email.send()
        return response

the pdf is rendered successfully but not sent by mail ?


Solution

  • from weasyprint import HTML
    from django.template.loader import render_to_string
    from django.core.mail import send_mail, EmailMultiAlternatives
    
    
    mail = EmailMultiAlternatives(
        'title',
        'text',
        from_email,
        [to_email,],
    )
    mail.attach_alternative(html_content, "text/html")
        
    render_from_template = render_to_string('template.html', context={'context': 'context'})
    pdf_file = HTML(string=file)
    
    mail.attach(f'ticket.pdf', pdf_file.write_pdf(), 'application/pdf')
    
    mail.send()
    

    EDIT : You can also use get_template()

    from django.template.loader import render_to_string, get_template
    
    def create_pdf(context):
    
    
        template_name = 'template.html'
        template = get_template(template_name)
        html = template.render(context)
        pdf_binary = HTML(string=html).write_pdf()
    
        return pdf_binary
    
    context = {'foo':'bar'}
    mail.attach(f'ticket.pdf', create_pdf(context), 'application/pdf')