Dynamically generate PDF and email it using django

别说谁变了你拦得住时间么 提交于 2019-12-03 06:57:06

Ok I've figured it out.

The second argument in attach() expects a string. I just used a file object's read() method to generate what it was looking for:

from django.core.mail import EmailMessage

message = EmailMessage('Hello', 'Body goes here', 'from@example.com',
    ['to1@example.com', 'to2@example.com'], ['bcc@example.com'],
    headers = {'Reply-To': 'another@example.com'})
attachment = open('myfile.pdf', 'rb')
message.attach('myfile.pdf',attachment.read(),'application/pdf')

I ended up using a tempfile instead, but the concept is the same as an ordinary file object.

Generate the file temp.

from django.utils import timezone    
from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

def generate_pdf(pk):
    y = 700
    buffer = BytesIO()
    p = canvas.Canvas(buffer, pagesize=letter)
    p.setFont('Helvetica', 10)
    p.drawString(220, y, "PDF generate at "+timezone.now().strftime('%Y-%b-%d'))
    p.showPage()
    p.save()
    pdf = buffer.getvalue()
    buffer.close()
    return pdf

Attach the PDF to message

from django.core.mail import EmailMessage
def send(request)
    pdf = generate_pdf(pk)
    msg = EmailMessage("title", "content", to=["email@gmail.com"])
    msg.attach('my_pdf.pdf', pdf, 'application/pdf')
    msg.content_subtype = "html"
    msg.send()

Based on the example in your link:

message.attach('design.png', img_data, 'image/png')

Wouldn't your content for a pdf just be the same output that you would normally write to the pdf file? Instead of saving the generated_pdf_data to myfile.pdf, plug it into the content field of the message.attach:

message.attach('myfile.pdf', generated_pdf_data, 'application/pdf')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!