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

Posted

技术标签:

【中文标题】在 django 中发送带附件的电子邮件【英文标题】:Sending emails with attachment in django 【发布时间】:2011-01-28 07:28:48 【问题描述】:

我正在尝试发送带有 django 中附加的一些图像的电子邮件。使用的代码是这个 sn-p:http://www.djangosnippets.org/snippets/1063/。我不知道,为什么附件部分返回核心错误。

代码。 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 我做错了什么?

【问题讨论】:

【参考方案1】:

您发布的错误回溯似乎与实际代码没有任何关系 - 这似乎是中间件的某种问题(大概是在呈现 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)

【讨论】:

我可以使用 Django 的 send_email() 方法来附加文件吗,或者在这种情况下我必须使用 EmailMessage 类。 @chiragsoni 最好直接使用 EmailMessage 类。见docs.djangoproject.com/en/dev/_modules/django/core/mail/…【参考方案2】:

在 Django 中发送带有附件的邮件

forms.py

from django import forms


class SendMailForm(forms.Form):
    email_id = forms.EmailField()
    email_cc = forms.EmailField()
    email_bcc = forms.EmailField()
    subject = forms.CharField(max_length=200)
    msg = forms.CharField(widget=forms.Textarea)
    attachment = forms.FileField()

views.py

from django.core.mail import EmailMessage
from django.shortcuts import render, HttpResponse, HttpResponseRedirect

from .forms import SendMailForm


# Create your views here.
def simple_send_mail(request):
    if request.method == 'POST':
        fm = SendMailForm(request.POST or None, request.FILES or None)
        if fm.is_valid():
            subject = fm.cleaned_data['subject']
            message = fm.cleaned_data['msg']
            from_mail = request.user.email
            print(from_mail)
            to_mail = fm.cleaned_data['email_id']
            to_cc = fm.cleaned_data['email_cc']
            to_bcc = fm.cleaned_data['email_bcc']
            print(fm.cleaned_data)
            attach = fm.cleaned_data['attachment']
            if from_mail and to_mail:
                try:
                    mail = EmailMessage(subject=subject, body=message, from_email=from_mail, to=[to_mail], bcc=[to_bcc],
                                        cc=[to_cc]
                                        )
                    mail.attach(attach.name, attach.read(), attach.content_type)
                    mail.send()
                # except Exception as ex:
                except ArithmeticError as aex:
                    print(aex.args)
                    return HttpResponse('Invalid header found')
                return HttpResponseRedirect('/mail/thanks/')
            else:
                return HttpResponse('Make sure all fields are entered and valid.')
    else:
        fm = SendMailForm()
    return render(request, 'mail/send_mail.html', 'fm': fm)

settings.py

# Email Configurations

# DEFAULT_FROM_EMAIL = ''
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@abc.com'
EMAIL_HOST_PASSWORD = '************'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

send_mail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mail</title>
</head>
<body>
    <form method="POST" action="" enctype="multipart/form-data">
        % csrf_token %
        <center><h1>Mail send from "request.user.email"</h1></center>
        fm.as_p
        <input type="submit" value="Send">
    </form>
</body>
</html>

【讨论】:

以上是关于在 django 中发送带附件的电子邮件的主要内容,如果未能解决你的问题,请参考以下文章

在 golang 中使用 gmail API 发送带附件的电子邮件

在 gmail android 应用程序中发送带附件的电子邮件时出错

自动化测试发送带附件的邮件

PHP - 发送带附件的电子邮件不显示邮件内容

如何仅使用电子邮件应用程序发送带附件的电子邮件?

Word邮件合并不能发送HTML格式以及怎么带附件?