发送带附件的电子邮件时,“InMemoryUploadedFile”对象没有属性“rfind”

时间:2014-02-21 15:45:53

标签: python django email django-forms email-attachments

我有一个通用的创建视图,如果它有效,则使用我的ModelForm中的数据发送电子邮件。电子邮件还应该有来自表单上文件字段的附件。

但我似乎无法弄清楚如何附加文件,并发送电子邮件。我目前收到'InMemoryUploadedFile' object has no attribute 'rfind'错误。

我的观点:

from __future__ import absolute_import

from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView
from django.core.urlresolvers import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.core.mail import send_mail, send_mass_mail, EmailMessage

from .models import Job, Application
from .forms import ApplicationForm

class JobListView(ListView):
    model = Job

    def get_context_data(self, **kwargs):
        context = super(JobListView, self).get_context_data(**kwargs)
        context['jobs'] = self.is_expired=False
        return context

class JobDetailView(DetailView):
    model = Job

class ApplicationCreateView(CreateView):
    model = Application
    form_class = ApplicationForm
    success_url = 'submitted/'

    def dispatch(self, *args, **kwargs):
        self.job = get_object_or_404(Job, slug=kwargs['slug'])
        return super(ApplicationCreateView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        #Get associated job and save
        self.object = form.save(commit=False)
        self.object.job = self.job
        self.object.save()

        # Gather cleaned data for email send
        first_name = form.cleaned_data.get('first_name')
        last_name = form.cleaned_data.get('last_name')
        email_address = form.cleaned_data.get('email_address')
        phone_number = form.cleaned_data.get('phone_number')
        salary_requirement = form.cleaned_data.get('salary_requirement')
        description = form.cleaned_data.get('description')
        portfolio_url = form.cleaned_data.get('portfolio_url')
        can_relocate = form.cleaned_data.get('can_relocate')
        start_date = form.cleaned_data.get('start_date')
        resume = form.cleaned_data.get('resume')

        #Compose message
        email = EmailMessage()
        email.body = 'Name:' + first_name + last_name + '\n' + 'Email:'  + email_address + '\n' + 'Phone number:' + str(phone_number) + '\n' + 'Salary requirement:' + str(salary_requirement) + '\n' + 'Description:' + description + '\n' + 'Portfolio:' + portfolio_url + '\n' + 'Can relocate:' + str(can_relocate) + '\n' + 'Start date:' + str(start_date)
        email.subject = 'A new application has been submitted'
        email.from_email = 'Job application <noreply@email.com>'
        email.to = ['email@email.com',]
        email.attach_file(resume)
        email.send()
        return HttpResponseRedirect(self.get_success_url())

    def get_context_data(self, *args, **kwargs):
        context_data = super(ApplicationCreateView, self).get_context_data(*args, **kwargs)
        context_data.update({'job': self.job})
        return context_data

我的表格:

from django.forms import ModelForm

from  .models import Application

class ApplicationForm(ModelForm):
    class Meta:
        model = Application
        fields = [
            'first_name',
            'last_name',
            'email_address',
            'phone_number',
            'salary_requirement',
            'resume',
            'portfolio_url',
            'description',
            'can_relocate',
            'start_date',
        ]
    def clean(self):
        cleaned_data = super(ApplicationForm, self).clean()
        resume = cleaned_data.get('resume')
        resume_ext = resume.name.lower().split('.')[1]
        if not resume_ext in ('pdf', 'doc', 'docx'):
            msg = u"Your file must be a PDF or DOC file type."
            self._errors["resume"] = self.error_class([msg])
            del cleaned_data["resume"]
        return cleaned_data

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

原来我需要利用Django的EmailMessage课程,如文档中所示:https://docs.djangoproject.com/en/1.6/topics/email/#emailmessage-objects