如何将保存在 Django FileField 中的文件作为附件发送?
如何发送包含保存在 FileField 中的文件的邮件?我不知道如何访问下面代码中的文件。
mail = EmailMessage(subject, message, 'from@from,com', ['[email protected]'])
mail.attach(?, ?, 'application/pdf')
mail.send()
编辑
文件
f = list_pca.pdf_file.open(mode='rb')
我尝试打开其中 list_pca 是实例的
class ListPCA(models.Model):
pdf_file = models.FileField(upload_to=get_file_path_j, null=True, blank=True)
,但收到错误“没有这样的文件或目录”,因为路径错误。
并
list_pca.pdf_file.path
返回错误的路径。由于 upload_to
选项,它不是应该知道文件在哪里吗?
谢谢
谢谢
how can I send a mail with a file saved in a FileField? I don't know how to access the file in the code below.
mail = EmailMessage(subject, message, 'from@from,com', ['[email protected]'])
mail.attach(?, ?, 'application/pdf')
mail.send()
EDIT
I tried to open the file with
f = list_pca.pdf_file.open(mode='rb')
where list_pca is an instance of
class ListPCA(models.Model):
pdf_file = models.FileField(upload_to=get_file_path_j, null=True, blank=True)
but I get an error "No such file or directory", because the path is wrong.
and
list_pca.pdf_file.path
return the wrong path too. Isn't it supposed to know where is the file thanks to the upload_to
option?
Thanks
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于您使用的是 EmailMessage,因此您也可以将附件 kwarg 传递给它。
Since you're using EmailMessage, you can just pass it the attachments kwarg as well.
通常,就像 aganders3 建议的那样,我会使用:
但是,我注意到它对于包含空格的附件会失败。
Ordinarily, like aganders3 suggested, I would use:
But, I noted that it fails for attachments containing spaces.
我认为这可以做到:
mail.attach(os.path.basename(myfile.name), myfile.read(), 'application/pdf')
我可能会忽略 MIME 编码步骤,但 IIRC mail.attach 会做到这一点。
I think this will do it:
mail.attach(os.path.basename(myfile.name), myfile.read(), 'application/pdf')
I might be overlooking a MIME-encoding step, but IIRC mail.attach will do that.
尝试:
Try:
其他建议应该有效,但您也可以这样做:
您可以选择传递 MIME 类型作为第二个参数,但如果您不提供它,它只是尝试从文件名中找出它。
The other suggestions should work, but you can also do:
You can optionally pass the MIME-type as the second argument, but it just tries to figure it out from the file name if you don't provide it.