在Django中,如何保存已上传到内存中的文件作为电子邮件附件? [英] In Django, how do I save a file that has been uploaded in memory as an email attachment?
问题描述
我正在为客户建立电子邮件网关,需要能够将他们上传的文件附加到电子邮件中.我正在使用 EmailMultiAlternatives
发送电子邮件和用于上传的 FileField
.当我尝试将两者连接时会发生问题.我认为以下逻辑.
I am building an email gateway for our clients and need to be able to attach the files they upload to the email. I am using EmailMultiAlternatives
to send the email and a FileField
for the upload. The problem happens when I try to connect the two. I have the following logic in my view.
if request.method == 'POST':
form = MyForm(request.POST, request.FILES)
if form.is_valid():
...
email = EmailMultiAlternatives(...)
email.attach(request.FILES['image'])
else:
form = MyForm()
这将导致未提供异常消息"和调试中的以下值:
This results in "No exception message supplied" and the following values in debug:
content: None
filename: <InMemoryUploadedFile: ImageFile.png (image/png)>
mimetype: None
因此,由于某种原因,似乎没有文件内容.不知道这是怎么回事.文档中的示例将文件保存到模型中,但是没有模型可将文件保存到此处.理想情况下,我只想将文件内容直接传递给attach方法并继续发送.关于如何进行这项工作的任何想法?
So it looks like for some reason, there is no file content. Not sure what's going on here. Examples in the docs save the file to a model, but there is no model to save the file to here. Ideally, I would just like to pass the file content directly to the attach method and send it on. Any ideas on how to make this work?
推荐答案
看起来我比原先想象的要近.以下是技巧.
Looks like I was closer than I originally thought. The following did the trick.
import mimetypes
from django.core.mail import EmailMultiAlternatives
if request.method == 'POST':
form = MyForm(request.POST, request.FILES)
if form.is_valid():
...
file = request.FILES['image']
email = EmailMultiAlternatives(...)
email.attach(file.name, file.file.getvalue(), mimetypes.guess_type(file.name)[0])
else:
form = MyForm()
这利用了第二种文件附件方法在Django文档中,而我最初尝试的是第一个.
This makes use of the second method of file attachment in the Django docs, whereas I was originally attempting the first.
这篇关于在Django中,如何保存已上传到内存中的文件作为电子邮件附件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!