在Django中发送带附件的电子邮件

时间:2017-04-17 14:34:18

标签: python django file email

我正在尝试发送带有附件的Django表单并发送电子邮件,但我无法弄清楚如何发送文件(由用户上传)而不在本地保存。 我有我的表格:

class PrintForm(forms.Form):
    contact_name = forms.CharField(required=True)
    contact_email = forms.EmailField(required=True)
    supervisor = forms.ChoiceField(
        choices=[(str(sup.email), str(sup.name)) for sup in Supervisors.objects.all()]
    )
    file = forms.FileField()
    content = forms.CharField(
        required=True,
        widget=forms.Textarea
    )

和我的观点:

def print(request):
   #  context = dict()
   #  context['printers'] = Printer.objects.all()
   #   return render(request, 'threeD/print.html', context)

   if request.method == 'POST':
        form = PrintForm(data=request.POST, request = request)

        if form.is_valid():
            contact_name = request.POST.get('contact_name', '')
            contact_email = request.POST.get('contact_email', '')
            form_content = request.POST.get('content', '')
            supervisor = form.cleaned_data['supervisor']
            template = get_template('threeD/email/contact_template_for_printing.txt')
            context = Context({
                'contact_name': contact_name,
                'supervisor': supervisor,
                'contact_email': contact_email,
                'form_content': form_content,
            })
            content = template.render(context)
            subject = "New message"

            try:
                email = EmailMessage(
                    subject,
                    content,
                    contact_email,
                    [supervisor],
                    headers={'Reply-To': contact_email}
                )
                #email.attach(...)
                email.send()
            except:
                return "Attachment error"

            messages.success(request, "Thank you for your message.")
            return redirect('/index/print/')

   else:
            form = PrintForm(request=request)
   context_dict = {}
   context_dict['printers'] = Printer.objects.all()
   context_dict['form'] = form
   return render(request, 'threeD/print.html', context_dict)

所以在我看来,当我发送电子邮件时,是否有办法调用email.attach(file)将文件附加到邮件并发送但没有在本地保存文件? (表单和视图工作正常,没有文件功能实现)

编辑:
这是HTML代码片段,我在其中调用表单:

 <div class="panel-body">
        <form role="form" action="" method="post">
            {% csrf_token %}
            {% load bootstrap %}
               {{ form|bootstrap }}

            <div class="text-center">
                <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-send"></span>    Send a message</button>
            </div>
        </form>
 </div>

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

这样的事情:

def send_email(request):
    ...
    email = EmailMessage(
        subject,
        content,
        contact_email,
        [to],
        headers={'Reply-To': contact_email}
    )
    if request.FILES:
        uploaded_file = request.FILES['file'] # file is the name value which you have provided in form for file field
        email.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type)
    email.send()