我需要models.FileField
使用 Django 作为电子邮件附件发送。我已经看到了显示如何使用原始request.FILES
数据(仍包含 Content-Type)执行此操作的片段,但是一旦您已经将文件保存在models.FileField
. 内容类型似乎无法从models.FileField
.
有人可以给我一个例子来说明这将如何工作吗?我开始认为保存文件时可能必须将 Content-Type 存储在模型中。
谢谢!
我需要models.FileField
使用 Django 作为电子邮件附件发送。我已经看到了显示如何使用原始request.FILES
数据(仍包含 Content-Type)执行此操作的片段,但是一旦您已经将文件保存在models.FileField
. 内容类型似乎无法从models.FileField
.
有人可以给我一个例子来说明这将如何工作吗?我开始认为保存文件时可能必须将 Content-Type 存储在模型中。
谢谢!
在 Django 中,将 models.FileField 文件附加到电子邮件消息中既简单又好用:
from django.core.mail import EmailMultiAlternatives
kwargs = dict(
to=to,
from_email=from_addr,
subject=subject,
body=text_content,
alternatives=((html_content, 'text/html'),)
)
message = EmailMultiAlternatives(**kwargs)
message.attach_file(model_instance.filefield.path)
message.send()
另一种方法:
from django.core.mail.message import EmailMessage
msg = EmailMessage(subject=my_subject, body=my_email_body,
from_email=settings.DEFAULT_FROM_EMAIL, to=[to_addressed])
msg.attach_file(self.my_filefield.path) # self.my_filefield.file for Django < 1.7
msg.send(fail_silently=not(settings.DEBUG))
我正在使用django-.path
storages等等
NotImplementedError: This backend doesn't support absolute paths.
为了避免这种情况,我只需打开文件,阅读它,猜测 mimetype 并稍后关闭它,但必须使用.attach
而不是.attach_file
魔法。
from mimetypes import guess_type
from os.path import basename
f = model.filefield
f.open()
# msg.attach(filename, content, mimetype)
msg.attach(basename(f.name), f.read(), guess_type(f.name)[0])
f.close()
I would just not supply a content type and let the recipient's email client work it out. Unless it will be something unusual it shouldn't be a problem.
RFC2616 states:
If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource.
but... If you want to specify it then storing the content type on upload is a very good idea. It should be noted that django's own docs say to verify the data from users
If you are on a *unix OS you could try to guess/inspect it:
import subprocess
subprocess.check_output(['file', '-b', '--mime', filename])