在Django中发送带有附件的电子邮件 [英] Sending email with attached file in Django

查看:49
本文介绍了在Django中发送带有附件的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以Django形式发送和发送带有附件的文件,但是我不知道如何发送文件(由用户上传)而不在本地保存.我有我的表格:

I am trying to send and email in Django forms with attached file, but i cant figure out how to send the file(uploaded by user) without saving it locally. I have my form:

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),该方法会将文件附加到邮件中并发送出去,但又不会在本地保存文件?(窗体和视图可以正常运行,而无需执行文件功能)

So in my view, when i am sending an email, is there a way to call email.attach(file) which would attach file to a mail and send it but without locally saving the file? (form and view works fine, without file feature implementation)


这是HTML代码段,在这里我要求使用以下形式:


here is HTML code snippet, where i call for the form:

 <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>

任何帮助将不胜感激.谢谢!

Any help would be very much appreciated. Thanks!

推荐答案

类似以下内容:

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()

这篇关于在Django中发送带有附件的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆