English 中文(简体)
Dynamically generate PDF and email it using django
原标题:

I have a django app that dynamically generates a PDF (using reportlab + pypdf) from user input on an HTML form, and returns the HTTP response with an application/pdf MIMEType.

I want to have the option between doing the above, or emailing the generated pdf, but I cannot figure out how to use the EmailMessage class s attach(filename=None, content=None, mimetype=None) method. The documentation doesn t give much of a description of what kind of object content is supposed to be. I ve tried a file object and the above application/pdf HTTP response.

I currently have a workaround where my view saves a pdf to disk, and then I attach the resulting file to an outgoing email using the attach_file() method. This seems wrong to me, and I m pretty sure there is a better way.

问题回答

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 )

I found this to work

message.attach( myfile.pdf , pdf.getvalue() ,  application/pdf )

When using

message.attach( myfile.pdf , pdf.read() ,  application/pdf )

The pdf cannot be opened as it s corrupt





相关问题
Angle brackets in php

I want to store angle brackets in a string in PHP because i want to eventually use mail() to send an HTML email out. The following is the code that doesn t seem to work. while(...) { $msg .= "<...

authlogic auto_register feature using my options

I have auto registration working with authlogic using gaizka s version of authlogic_openid which I found on Github since pelle s original addition of the feature seemed to cause issues. http://...

Zend 邮件问题,涉及外国char子+ com子

泽斯德邮局在名称被定为具有外国性质(如“保”)和 com(”)的物品时,就放弃了一种例外(因为邮局(邮局)退回假)。 重新提出以下守则。

How to track an email in Java?

How I can track an email? I m using java on the server side for sending emails. I want to track whether it is delivered , opened, etc... How I can do that ?

Web Link in a mail is not rendering as link in yahoo

string from = "abc@gmail.com"; string to = "xyz@gmail.com,xyz@yahoo.co.in"; string password="abcxyz"; MailMessage mail = new System.Net.Mail.MailMessage(); mail.To.Add(to); mail.From = new ...

SharePoint - Approaching Website Storage Limit Email

How can i go about changing the distribution list as well as the email text for the email that goes out to site collection admin when a site collection approaches it s size limit? Thanks for your ...

How to create an email mailing list

Im creating a coming soon page for a website im developing, and im adding an option for the user to enter their email address so we can email them when the site is up. How do I do this?

CCNet email does not include MSBuild results

We re using CCNet 1.4.4.83 but when an MSBuild task fails, we don t get the MSBuild results (i.e. missing file or whatever reason the compile failed) in the email notification. I do see the build ...

热门标签