如何将文件缓冲区附加到Django Mail Queue

时间:2019-07-02 01:07:17

标签: python django attachment

我一直在尝试将xls缓冲区或pdf缓冲区附加到Django邮件队列,但是我不能。

我尝试使用FileResponse或HttpResponse并将其转换为Django文件对象,但这也失败了。

这是我尝试过的:

new_message = MailerMessage()
new_message.subject = "Test"
new_message.to_address = "test@gmail.com"
new_message.from_address = "noreply@gmail.com"

file_attachment = FileResponse('file_content_buffer', content_type='application/vnd.ms-excel')

new_message.add_attachment(file_attachment)     

new_message.save()

我收到一个错误: 'FileResponse' object has no attribute 'file'。 我知道附件方法会等待文件对象,如文档所述: https://django-mail-queue.readthedocs.io/en/latest/usage.html#attaching-files

有什么主意吗?谢谢。

解决方案:
小小骇客地看着邮件队列代码做什么。你觉得呢?

from mailqueue.models import MailerMessage, Attachment

new_message = MailerMessage()
new_message.subject = "Subject Mail"
new_message.to_address = 'test@gmail.com'
new_message.from_address = 'noreply@gmail.com'

new_message.save()

attachment = Attachment()
attachment.file_attachment.save('file.xlsx',ContentFile(excel_buffer),save=False)
attachment.email = new_message
attachment.original_filename = 'file.xlsx'
try:
    new_attachment.save()
except Exception as e:
    new_attachment.file_attachment.delete()

1 个答案:

答案 0 :(得分:0)

尝试此 Django 2.1版

file_attachment = FileResponse(open('myfile.xls', 'rb'),as_attachment=True,'myfile.xls')

Source是有关如何使用FileResponse的django官方文档。

使用HTTPResponse Django 1.9 添加答案:

file_attachment = HttpResponse('myfile.xls', content_type='application/vnd.ms-excel') 
file_attachment['Content-Disposition'] = 'attachment; filename="myfile.xls"'

Source