我正在尝试创建一个网页,用户可以在其中填写表单并通过电子邮件向我发送他们的姓名,电子邮件地址,消息和图片。
我的问题是将图片附加到电子邮件中。当代码运行时,图像将与我的其他媒体文件一起上传到我的媒体根目录,但它会抛出FileNotFoundError [Errno 2]没有这样的文件或目录:'media / 2016/10/14 / image.png'
这是我的models.py:
class UploadedImage(models.Model):
uImage = models.FileField(upload_to='media/%Y/%m/%d')
forms.py:
class QuoteForm(forms.Form):
name = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
uImage = forms.FileField(required=False, help_text='5mb max.')
message = forms.CharField(widget=forms.Textarea)
views.py:
def quote(request):
form = QuoteForm(request.POST, request.FILES)
if form.is_valid():
name = form.cleaned_data['name']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
subject = "Quote"
message = "From: " + name + "\n" + "Return Email: " + from_email + "\n" + "Subject: " + subject + "\n" + "Message: " + message
newImage = UploadedImage(uImage = request.FILES['uImage'])
newImage.save()
msg = EmailMessage(subject, message, from_email, ['zbloss@emich.edu'], reply_to=[from_email])
image_url = newImage.uImage.url
msg.attach_file(image_url)
try:
msg.send()
except BadHeaderError:
return HttpResponse('Invalid header found')
return HttpResponseRedirect('/thankyou')
return render(request, "quote.html", {'form': form})
答案 0 :(得分:1)
您将(不存在的)网址传递给msg.attach_file
。您需要在磁盘上传递文件的位置:
msg.attach_file(os.path.join(settings.MEDIA_ROOT, newImage.uImage.name))