【发布时间】:2018-06-09 23:22:23
【问题描述】:
我有一个应用程序,用户可以通过填写表格与我联系,用户只需在表格中填写他的详细信息以及他的电子邮件和主题。
代码没有引发错误,但我设置完所有内容后无法收到邮件,但联系人详细信息已存储在数据库中,因为我希望它被存储。
下面是我的代码。
Models.py
class Contact(models.Model):
name = models.CharField(max_length=100)
message = models.TextField()
sender = models.EmailField()
phone = models.CharField(max_length=10)
cc_myself = models.BooleanField(blank=True)
time = models.DateTimeField(auto_now_add=True, db_index=True)
def __str__(self):
return 'Message for {}'.format(self.sender)
Forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['name', 'sender', 'phone', 'message', 'cc_myself']
Views.py
def contact(request):
if request.method == 'POST':
contact_form = ContactForm(request.POST)
if contact_form.is_valid():
name = contact_form.cleaned_data['name']
message = contact_form.cleaned_data['message']
sender = contact_form.cleaned_data['sender']
phone = contact_form.cleaned_data['phone']
cc_myself = contact_form.cleaned_data['cc_myself']
recipients = ['xxxx@gmail.com']
if cc_myself:
recipients.append(sender)
send_mail(name, message, sender, recipients)
contact_form.save()
messages.success(request, 'Message sent successfully')
return redirect('contact:contact')
else:
messages.error(request, 'Error sending your Message')
else:
contact_form = ContactForm(request.POST)
context = {
"contact_form": contact_form,
}
template = 'contact.html'
return render(request, template, context)
gmail 服务器
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'xxx@gmail.com'
EMAIL_HOST_PASSWORD = 'xxxx'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
终端输出
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Subject: adie Ugbe
From: abcd@gmail.com
To: xxxx@gmail.com
Date: Sun, 07 Jan 2018 11:11:10 -0000
Message-ID: <20180107111110.29855.10393@1.0.0.127.in-addr.arpa>
oh oh no ooo dddddddd se skan
-------------------------------------------------------------------------------
Successful
【问题讨论】:
-
在您的 send_mail 函数上使用 fail_silently=False 进行测试 send_mail(name, message, sender, recipients, fail_silently=False) 将引发 smtplib.SMTPException。也许是 smtp 服务器的一个例外。
-
您检查过邮箱中的“垃圾邮件”文件夹吗?
-
是的。它不在那里。甚至在发送电子邮件的已发送邮件中也没有
-
请搜索其他答案:stackoverflow.com/questions/31324005/… 确保在设置中:EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
-
发现了问题。我意识到我的设置文件中有
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'。删除它解决了问题。它与 smtp 冲突