【问题标题】:Sending Email attachment using django :使用 django 发送电子邮件附件:
【发布时间】:2016-06-10 16:44:58
【问题描述】:

我正在尝试附加文件并将其发送到电子邮件。 但它会将我重定向到错误页面,即error.html。文件未发送到电子邮件。你能帮我解决这个错误吗?我是 django 的新手,感谢您的帮助。谢谢你

models.py

class Email(models.Model):
    email = models.EmailField()
    subject = models.CharField(max_length=100)
    attach = models.FileField()
    message = models.CharField(max_length=250)

forms.py

from django import forms
from .models import Email
from django.core.mail import EmailMessage


class EmailForm(forms.ModelForm):
    class Meta:
        model = Email
        fields = ['email', 'attach','subject' ,'message']


    def _clean_email(self):
        email = self.cleaned_data.get('email')
        return email


    def _clean_subject(self):
        subject = self.cleaned_data.get('subject')
        return subject


    def _clean_message(self):
        message = self.cleaned_data.get('message')
        return message

    def _clean_attach(self):
        attach = self.cleaned_data.get('attach')
        return attach

views.py

def send_email(request):
    if request.method != 'POST':
        form = EmailForm()
      context = {
            "form": form
        }
        return render(request,'email.html', context)

    form = EmailForm(request.POST, request.FILES)

    if form.is_valid():
        subject = form.cleaned_data.get("subject")
        message = form.cleaned_data.get("message")
        email   = form.cleaned_data.get("email")
        a  = request.FILES['attach']
        try:


            mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, 'vamagithub@gmail.com')
            mail.attach_file(a.name, a.read(), a.content_type)
            mail.send()
            context ={
                "message": 'Sent email to %s' % email
            }
            return render(request,'email.html',context)

        except:
            context = {
                "message": 'Either the attachment is too  big or corrupt'
            }
            return render(request,'error.html',context)

        return render(request,'email.html', {'message': 'Unable to send email. Please try again later'})

【问题讨论】:

  • 删除 except 块以查看实际错误。
  • 返回 email.html 页面

标签: python django email sendmail


【解决方案1】:

您使用了 attach_file。因为您必须提供文件路径以传递这些参数 a.name、a.read()、a.content_type。您只使用 attach(a.name, a.read(), a.content_type)。欲了解更多信息,请阅读this

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2016-11-30
    • 2011-01-28
    • 2017-06-11
    相关资源
    最近更新 更多