2012-04-30 313 views
9

当使用发送电子邮件的视图什么也没有发生,我然后进入send_mail(...)到python shell,它返回1,但我没有收到任何电子邮件。Django send_mail不起作用

这是我的settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' 
EMAIL_HOST = 'smtp.gmail.com' 
EMAIL_PORT = 587 
EMAIL_HOST_USER = '[email protected]' 
EMAIL_HOST_PASSWORD = '[email protected]' 
EMAIL_USE_TLS = True 

这是视图:

def send_email(request): 
    send_mail('Request Callback', 'Here is the message.', '[email protected]', 
     ['[email protected]'], fail_silently=False) 
    return HttpResponseRedirect('/') 
+0

你检查了垃圾邮件收件箱吗?你创建了SPF记录吗? http://support.google.com/a/bin/answer.py?hl=en&answer=33786 – jpic

回答

10

调整设置这样的:

DEFAULT_FROM_EMAIL = '[email protected]' 
SERVER_EMAIL = '[email protected]' 
EMAIL_USE_TLS = True 
EMAIL_HOST = 'smtp.gmail.com' 
EMAIL_PORT = 587 
EMAIL_HOST_USER = '[email protected]' 
EMAIL_HOST_PASSWORD = '[email protected]' 

调整你的代码:

from django.core.mail import EmailMessage 

def send_email(request): 
    msg = EmailMessage('Request Callback', 
         'Here is the message.', to=['[email protected]']) 
    msg.send() 
    return HttpResponseRedirect('/') 
0

如果不在乎防止头注入: (你应该关心它:https://docs.djangoproject.com/es/1.9/topics/email/#preventing-header-injection,但让我们继续)

settings.py

EMAIL_HOST = 'smtp.gmail.com' 
EMAIL_PORT = 587 
EMAIL_HOST_USER = '[email protected]' 
EMAIL_HOST_PASSWORD = 'pass' 
EMAIL_USE_TLS = True 

views.py(例如) :

from django.views.generic import View 
from django.core.mail import send_mail 
from django.http import HttpResponse, HttpResponseRedirect 

class Contacto(View): 
     def post(self, request, *args, **kwargs): 
      data = request.POST 
      name = data.get('name', '') 
      subject = "Thanks %s !" % (name) 
      send_mail(subject, data.get('message', ''), '[email protected]', [data.get('email', '')], fail_silently=False) 
     return HttpResponseRedirect('/') 

这是发送电子邮件的危险方式

当您第一次尝试发送电子邮件时,您会收到一封谷歌邮件,建议您不要这样做。 您必须'激活''不太安全的应用程序'(https://www.google.com/settings/security/lesssecureapps)并重试。第二次工作。