【问题标题】:Django: send email on form submitionDjango:在提交表单时发送电子邮件
【发布时间】:2019-04-24 15:27:22
【问题描述】:

用户在我的页面上提交表单后,我需要发送一封电子邮件(这仍在开发中,但很快就会投入生产)。

我已阅读此other answer,但在我提交表单后,我没有收到任何电子邮件(我已将我的个人电子邮件用作发件人和收件人,用于测试)。

我需要修改什么?

PLUS: 如何通过电子邮件发送图像?有这方面的教程吗?提交表单后我需要发送专业的电子邮件。

settings.py

EMAIL_HOST = 'smtp.gmail.com'  # since you are using a gmail account
EMAIL_PORT = 587  # Gmail SMTP port for TLS
EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'oma.oma@gmail.com' #Not my actual email
EMAIL_HOST_PASSWORD = 'MyPassword' #Not my actual password

views.py:

# here we are going to use CreateView to save the Third step ModelForm
class StepThreeView(CreateView):
    form_class = StepThreeForm
    template_name = 'main_app/step-three.html'
    success_url = '/'

    def form_valid(self, form):
        form.instance.tamanios = self.request.session.get('tamanios')  # get tamanios from session
        form.instance.cantidades = self.request.session.get('cantidades')  # get cantidades from session
        del self.request.session['cantidades']  # delete cantidades value from session
        del self.request.session['tamanios']  # delete tamanios value from session
        self.request.session.modified = True
        return super(StepThreeView, self).form_valid(form)

form.py:

from django.core.mail import send_mail

class StepThreeForm(forms.ModelForm):
    instrucciones = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = TamaniosCantidades
        fields = ('imagenes', 'instrucciones')

    def __init__(self, *args, **kwargs):
        super(StepThreeForm, self).__init__(*args, **kwargs)
        self.fields['instrucciones'].required = False

    def send_email(self):
        send_mail('Django Test', 'My message', 'oma.oma@gmail.com',
                  ['oma.oma@gmail.com'], fail_silently=False)

【问题讨论】:

  • 看来您没有在任何地方调用表单的 send_email 方法...
  • @ivissani 我该怎么做?

标签: django


【解决方案1】:

您可以在您的 Last Form 中像这样覆盖 save 方法:

 class StepThreeForm(forms.ModelForm):
      def save(self, commit=True):
          instance = super(StepThreeForm, self).save(commit=commit)
          self.send_email()
          return instance

       def send_email(self):
           image = self.cleaned_data.get('imagenes', None)
           msg = EmailMessage(
              'Hello',
              'Body goes here',
              'from@example.com',
              ['to1@example.com', 'to2@example.com'],
              headers={'Message-ID': 'foo'},
           )

           msg.content_subtype = "html"

           if image:
             mime_image = MIMEImage(image.read())
             mime_image.add_header('Content-ID', '<image>')
             msg.attach(mime_image)
           msg.send()

您可以查看SO Answer 了解有关如何从 Django 发送图像的更多详细信息

【讨论】:

  • send_email 方法中有未解决的引用:EmailMessageMIMEImage。所以尝试只更新保存方法并得到这个错误:'NoneType' object has no attribute '__dict__'
  • @OmarGonzales 更新了我的答案,错过了保存方法的返回语句
  • 尝试了更新的答案,但得到:Could not guess image MIME subtype 即使我没有附加任何图像。
  • 而不是msg.attach(mime_image),也许你可以使用msg.attach_file(obj.imagenes.path)并在send_email方法中传递这个obj,比如self.send_email(obj=instance)。有关文档,请参阅此处:docs.djangoproject.com/en/2.1/topics/email/…。更新方法签名以及def send_email(self, obj) :)
猜你喜欢
  • 2016-08-01
  • 2016-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-28
  • 2016-07-26
相关资源
最近更新 更多