【问题标题】:Django EmailMultiAlternatives not attaching pdfDjango EmailMultiAlternatives 未附加 pdf
【发布时间】:2015-01-05 05:23:01
【问题描述】:

我在 Python 中有以下代码来发送带有附件 pdf 的电子邮件。

result_url = '%s%s?analysis_id=%s' % (
        constants.HOST_URL, reverse('results'), analysis.id)
pdf_filename = ''.join(['report', str(analysis_id), '.pdf'])
utils.convert_to_pdf(result_url, pdf_filename)

这是我的utils.convert_to_pdf

def convert_to_pdf(url, filename):
    command = "phantomjs export.js %s %s" % (url, filename)
    execute_command(command).communicate()

这就是我发送电子邮件的方式。

email_ids = []
if analysis.user is not None:
    email_ids.append(analysis.user.email)

if email is not None:
    email_ids.append(email)

body = ANALYSIS_EMAIL_BODY % (result_url)

try:
    message = EmailMultiAlternatives(ANALYSIS_EMAIL_SUBJECT, body, settings.EMAIL_SENDER, email_ids)
    message.attach('Report.pdf', pdf_filename, 'application/pdf')
    message.send() 
except Exception as ex:
    logging.error('Send mail failed: %s', ex)

现在我看到 PDF 文件已在我当前的文件夹中正确生成并附在邮件中,但邮件中的大小为 0KB,当我尝试打开文件时它会告诉我。

It may be damaged or use a file format that preview doesn't recognize

这里出了什么问题。

【问题讨论】:

    标签: python django email pdf


    【解决方案1】:

    您只是将文件名附加为文件的内容。

    您需要附加实际内容,而不是文件名。

    message.attach('Report.pdf', read_pdf_contents(), 'application/pdf')
    

    您的工作是确定如何从文件名中获取原始数据。

    类似于myfile_like_object.read()

    【讨论】:

      猜你喜欢
      • 2015-06-03
      • 2014-09-01
      • 1970-01-01
      • 2015-02-10
      • 2016-01-18
      • 2015-09-28
      • 2021-07-03
      • 2013-08-05
      • 2011-09-19
      相关资源
      最近更新 更多