这个问题有一些元素here,但没有最终答案。
有使用easy_pdf生成PDF的视图
from easy_pdf.views import PDFTemplateResponseMixin
class PostPDFDetailView(PDFTemplateResponseMixin,DetailView):
model = models.Post
template_name = 'post/post_pdf.html'
然后,我想将生成的PDF附加到以下电子邮件中:
@receiver(post_save, sender=Post)
def first_mail(sender, instance, **kwargs):
if kwargs['created']:
user_email = instance.client.email
subject, from_email, to = 'New account', 'contact@example.com', user_email
post_id = str(instance.id)
domain = Site.objects.get_current().domain
post_pdf = domain + '/post/' + post_id + '.pdf'
text_content = render_to_string('post/mail_post.txt')
html_content = render_to_string('post/mail_post.html')
# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.attach_file(post_pdf, 'application/pdf')
msg.send()
我也试过这个:
msg.attach_file(domain + '/post/' + post_id + '.pdf', 'application/pdf')
答案 0 :(得分:2)
我一直在寻找一种方法来附加easy_pdf生成的PDF而不保存临时文件。由于我无法在其他地方找到解决方案,因此我建议使用easy_pdf.rendering.render_to_pdf提交简短且有效的提案:
from easy_pdf.rendering import render_to_pdf
...
post_pdf = render_to_pdf(
'post/post_pdf.html',
{'any_context_item_to_pass_to_the_template': context_value,},
)
...
msg.attach('file.pdf', post_pdf, 'application/pdf')
如果你仍然对这种方法感兴趣,我希望它会有所帮助。
答案 1 :(得分:1)
不确定它是否有帮助,但我使用内置的EmailMessage附加我创建的PDF文件,用于报告我发送的电子邮件:
from django.core.mail import send_mail, EmailMessage
draft_email = EmailMessage(
#subject,
#body,
#from_email,
#to_email,
)
选项1:
# attach a file you have saved to the system... expects the path
draft_email.attach_file(report_pdf.name)
选项2:
# expects the name of the file object
draft_email.attach("Report.pdf")
然后,像你已经拥有的那样发送:
draft_email.send()
一些初步想法:您似乎正在尝试使用attach_file从系统附加文件,但它不在系统上。如果我正确地阅读您的代码,我会尝试使用attach
而不是attach_file
,因为pdf在您的内存中,而不是在系统中的LTS中。