我正在使用Django 1.10.3和Reportlab将html导出为pdf现在我想通过电子邮件发送相同的pdf.I能够生成pdf但无法通过电子邮件发送。请帮助我实现它。
以下是我的观点:
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()
更新
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()
错误:
环境:
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:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response
249. response = self._get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\New folder\Aditya\ProjectManagement\Project\views.py" in pdf_view
267. message.send()
File "C:\Python27\lib\site-packages\django\core\mail\message.py" in send
342. return self.get_connection(fail_silently).send_messages([self])
File "C:\Python27\lib\site-packages\django\core\mail\backends\smtp.py" in send_messages
107. sent = self._send(message)
File "C:\Python27\lib\site-packages\django\core\mail\backends\smtp.py" in _send
121. message = email_message.message()
File "C:\Python27\lib\site-packages\django\core\mail\message.py" in message
306. msg = self._create_message(msg)
File "C:\Python27\lib\site-packages\django\core\mail\message.py" in _create_message
394. return self._create_attachments(msg)
File "C:\Python27\lib\site-packages\django\core\mail\message.py" in _create_attachments
407. msg.attach(self._create_attachment(*attachment))
File "C:\Python27\lib\site-packages\django\core\mail\message.py" in _create_attachment
449. attachment = self._create_mime_attachment(content, mimetype)
File "C:\Python27\lib\site-packages\django\core\mail\message.py" in _create_mime_attachment
437. Encoders.encode_base64(attachment)
File "C:\Python27\lib\email\encoders.py" in encode_base64
45. encdata = _bencode(orig)
File "C:\Python27\lib\email\encoders.py" in _bencode
31. hasnewline = (s[-1] == '\n')
Exception Type: TypeError at /pdf_template/
Exception Value: 'file' object has no attribute '__getitem__'
答案 0 :(得分:1)
你试图直接使用send_email
,你应该做的是构建一个EmailMessage
对象,然后附加文件,并发送它。例如:
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()
当然,如果PDF在文件系统上,您也可以使用attach_file()
而不是attach()
。有关详细信息,请参阅文档的this section。
答案 1 :(得分:1)
我发现解决方案我所要做的就是将pdf保存在项目中,然后使用SimpleDocTemplate完成,然后通过给出它的位置来附加相同的文件。 这是我做的:
视图:
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')
答案 2 :(得分:1)
试试这个:
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.')