send_email在django中不起作用?

时间:2015-06-29 06:48:20

标签: python django

我写了一个通过django发送邮件的应用程序

models.py

from django.db import models

from django import forms

class EmailForm(forms.Form):

      firstname = forms.CharField(max_length=255)

      lastname = forms.CharField(max_length=255)

      email = forms.EmailField()

      subject = forms.CharField(max_length=255)

      botcheck = forms.CharField(max_length=5)

      message = forms.CharField()

views.py

from django.views.generic.base import TemplateView

from django.http import HttpResponseRedirect

from django.core.mail import send_mail, BadHeaderError

from models import EmailForm

from django.shortcuts import render

def sendmail(request):

    if request.method == 'POST':
      form = EmailForm(request.POST)
      if form.is_valid():
        firstname = form.cleaned_data['firstname']
        lastname = form.cleaned_data['lastname']
        email = form.cleaned_data['email']
        subject = form.cleaned_data['subject']
        botcheck = form.cleaned_data['botcheck'].lower()
        message = form.cleaned_data['message']
        if botcheck == 'yes':
         try:
            fullemail = firstname + " " + lastname + " " + "<" + email + ">"
            send_mail(subject, message, email, ['myemail@gmail.com'], fail_silently=False)
            return HttpResponseRedirect('/email/thankyou/')
         except:
            return HttpResponseRedirect('/email/')
        else:
          return HttpResponseRedirect('/email/')
    else:
        return HttpResponseRedirect('/email/') 

时的

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

它在控制台中显示。

但是当

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

它不会将电子邮件发送给指定的用户。  我的settings.py文件

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

EMAIL_USE_TLS   = True
EMAIL_HOST      =  'localhost'

EMAIL_PORT      = '8000'

我如何发送电子邮件?

1 个答案:

答案 0 :(得分:6)

您已将您的EMAIL主机指定为localhost,将其更改为可靠的电子邮件主机,例如Gmail。您的settings.py可以使用以下给定的设置来使用gmail smtp服务器发送电子邮件。你也必须改变端口。

EMAIL_USE_TLS = True 
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'username@gmail.com'
EMAIL_HOST_PASSWORD = 'password'

如果问题仍然存在,您必须允许less secure apps访问您的Gmail帐户。这是gmail最近对其帐户访问政策所做的更改。默认情况下,只有合格的域可以使用gmail身份验证(OAUTH2)机制发送电子邮件。要允许安全性较低的应用访问您的Gmail帐户,您必须登录Google开发者控制台。