I am using Django 1.10.3 and Reportlab to export html to pdf now I want to email the same generated pdf.I was able to generate the pdf but unable to email it. Please help me achieve it.
Here is my view:
def write_pdf_view(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename="mypdf.pdf"'
buff = StringIO()
menu_pdf = SimpleDocTemplate(buff, rightMargin=72,
leftMargin=72, topMargin=50, bottomMargin=18)
elements = []
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='centered',fontName='Italic', alignment=TA_CENTER))
elements.append(Paragraph('A good thing about WeasyPrint is that you can convert a HTML document to a PDF. So you can create a regular Django template, print and format all the contents and then pass it to the WeasyPrint library to do the job of creating the pdf.', style=styles["Normal"]))
menu_pdf.build(elements)
response.write(buff.getvalue())
buff.close()
Update:
subject = 'Welcome to Project Management Portal.'
message = 'Thank you for being part of us. n We are glad to have you. n Regards n Team Project Management'
from_email = settings.EMAIL_HOST_USER
to_list = [request.user.email, settings.EMAIL_HOST_USER]
message = EmailMessage(subject, message, from_email, to_list)
pdf = open('mypdf.pdf', 'rb')
message.attach('mypdf-2.pdf', pdf, 'application/pdf')
message.send()
Error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/pdf_template/
Django Version: 1.10.3
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Project',
'UserManagement',
'social.apps.django_app.default']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:Python27libsite-packagesdjangocorehandlersexception.py" in inner
39. response = get_response(request)
File "C:Python27libsite-packagesdjangocorehandlersbase.py" in _legacy_get_response
249. response = self._get_response(request)
File "C:Python27libsite-packagesdjangocorehandlersbase.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:Python27libsite-packagesdjangocorehandlersbase.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:New folderAdityaProjectManagementProjectviews.py" in pdf_view
267. message.send()
File "C:Python27libsite-packagesdjangocoremailmessage.py" in send
342. return self.get_connection(fail_silently).send_messages([self])
File "C:Python27libsite-packagesdjangocoremailbackendssmtp.py" in send_messages
107. sent = self._send(message)
File "C:Python27libsite-packagesdjangocoremailbackendssmtp.py" in _send
121. message = email_message.message()
File "C:Python27libsite-packagesdjangocoremailmessage.py" in message
306. msg = self._create_message(msg)
File "C:Python27libsite-packagesdjangocoremailmessage.py" in _create_message
394. return self._create_attachments(msg)
File "C:Python27libsite-packagesdjangocoremailmessage.py" in _create_attachments
407. msg.attach(self._create_attachment(*attachment))
File "C:Python27libsite-packagesdjangocoremailmessage.py" in _create_attachment
449. attachment = self._create_mime_attachment(content, mimetype)
File "C:Python27libsite-packagesdjangocoremailmessage.py" in _create_mime_attachment
437. Encoders.encode_base64(attachment)
File "C:Python27libemailencoders.py" in encode_base64
45. encdata = _bencode(orig)
File "C:Python27libemailencoders.py" in _bencode
31. hasnewline = (s[-1] == 'n')
Exception Type: TypeError at /pdf_template/
Exception Value: 'file' object has no attribute '__getitem__'
Try This:
def pdf_view(request):
fs = FileSystemStorage()
filename = 'mypdf.pdf'
if fs.exists(filename):
with fs.open(filename) as pdf:
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'inline; filename="mypdf.pdf"'
subject = 'Welcome to Project Management Portal.'
message = 'Thank you for being part of us. n We are glad to have you. n Regards n Team Project Management'
# message.attach = 'filename="mypdf.pdf", content_disposition="inline", data=open("mypdf.pdf", "rb")'
from_email = settings.EMAIL_HOST_USER
to_list = [request.user.email, settings.EMAIL_HOST_USER]
# send_mail(subject, message, message.attach, from_email, to_list)
message = EmailMessage(subject, message, from_email, to_list)
# pdf = open('media/mypdf.pdf', 'rb')
message.attach_file('media/mypdf.pdf')
message.send()
return response
else:
return HttpResponseNotFound('The requested pdf was not found in our server.')
You’re trying to just use send_email
directly, and what you should be doing is building an EmailMessage
object, and then attaching the file, and sending that. For example:
from django.core.mail import EmailMessage
message = EmailMessage(subject, body, from_email, to_list)
pdf = open('mypdf.pdf', 'rb')
message.attach('mypdf.pdf', pdf, 'application/pdf')
message.send()
Of course, if the PDF is on the filesystem, you might as well just use attach_file()
instead of attach()
. More info on that in this section of the docs.
I have found the solution all I had to do was to save the pdf in the project and I did it by using SimpleDocTemplate and then attached the same file by giving its location.
Here is what I did:
view:
def write_pdf_view(request):
doc = SimpleDocTemplate("media/mypdf.pdf", rightMargin=72, leftMargin=72, topMargin=-70)
styles = getSampleStyleSheet()
Story = [Spacer(1, 2 * inch)]
style = styles["Normal"]
paratext = ("A good thing about WeasyPrint is that you can convert a HTML document to a PDF. So you can create a regular Django template, print and format all the contents and then pass it to the WeasyPrint library to do the job of creating the pdf.")
p = Paragraph(paratext, style)
Story.append(p)
Story.append(Spacer(1, 0.2 * inch))
doc.build(Story)
subject = 'Welcome to Project Management Portal.'
message = 'Thank you for being part of us. n We are glad to have you. n Regards n Team Project Management'
from_email = settings.EMAIL_HOST_USER
to_list = [request.user.email, settings.EMAIL_HOST_USER]
message = EmailMessage(subject, message, from_email, to_list)
message.attach_file('media/mypdf.pdf')
message.send()
messages.add_message(request, messages.INFO, 'The PDF is sent Successfully !!')
return redirect('home')