2010-03-16 50 views
22

我試圖用django附帶的一些圖像發送電子郵件。使用的代碼是這個片段:http://www.djangosnippets.org/snippets/1063/。不知道爲什麼附件會給我一個核心錯誤。在django發送帶附件的電子郵件

代碼。 forms.py

from django import forms 
from common import slugify_unique 
from django.conf import settings 
from django.core.cache import cache 
from django.contrib.admin import widgets  
from django.shortcuts import get_object_or_404         

class WorkForm(forms.Form): 
    name = forms.CharField(label='Name and surname', max_length=64, required = True) 
    nick = forms.CharField(label='nickname', max_length=40, required = True) 
    email = forms.EmailField(label='e-mail', required = True) 
    image1 = forms.Field(label='sample photo', widget = forms.FileInput, required = True) 
    image2 = forms.Field(label='sample photo', widget = forms.FileInput, required = True) 
    image3 = forms.Field(label='sample photo', widget = forms.FileInput, required = True) 
    text = forms.CharField(label='Few words about you', widget=forms.Textarea, required = False) 

views.py

from forms import WorkForm 
from django.core.mail import send_mail, EmailMessage 


def work(request): 
    template = 'other/work.html'        

    if request.method == 'POST': 
     form = WorkForm(request.POST, request.FILES) 
     if form.is_valid(): 
      name = form.cleaned_data['name'] 
      nick = form.cleaned_data['nick'] 
      email = form.cleaned_data['email'] 
      subject = 'Work' 
      text = form.cleaned_data['text'] 
      image1 = request.FILES['image1'] 
      image2 = request.FILES['image2'] 
      image3 = request.FILES['image3'] 
      try: 
       mail = EmailMessage(subject, text, ['EMAIL_ADDRESS'], [email]) 
       mail.attach(image1.name, attach.read(), attach.content_type) 
       mail.attach(image2.name, attach.read(), attach.content_type) 
       mail.attach(image3.name, attach.read(), attach.content_type) 
       mail.send() 
       template = 'other/mail_sent.html' 
      except: 
       return "Attachment error" 
      return render_to_response(template, {'form':form}, 
           context_instance=RequestContext(request)) 
    else: 
     form = WorkForm()        
    return render_to_response(template, {'form':form}, 
        context_instance=RequestContext(request)) 

而這裏的誤差現場圖片: http://img201.imageshack.us/img201/6027/coreerror.png 我在做什麼錯?

回答

24

您發佈的錯誤追溯似乎與實際代碼沒有任何關係 - 它似乎是中間件的某種問題(可能是渲染500錯誤頁面時)。

但是,您的錯誤可能是由於您在調用mail.attach時使用了未定義的變量名稱attach而導致的。你沒有attach變量 - 你已經調用了發佈文件image1等,所以你應該使用這些名稱。

mail.attach(image1.name, image1.read(), image1.content_type) 
mail.attach(image2.name, image2.read(), image2.content_type) 
mail.attach(image3.name, image3.read(), image3.content_type) 
+0

正確的,謝謝! – owca