Django联系表格邮件发送[重复]
Posted
技术标签:
【中文标题】Django联系表格邮件发送[重复]【英文标题】:Django Contact form mail send [duplicate] 【发布时间】:2020-04-29 15:36:26 【问题描述】:我在 Django 中创建了一个名为“get in touch”(Bootstrap)的模态联系表,它 100% 正常工作,但我正忙于设置它以向我的电子邮件地址发送一封包含联系表内容的邮件。
但我收到一个错误提示
settings.EMAIL_HOST_USER
NameError: name 'settings' is not defined
我已经在 settings.py 文件中添加了邮件设置,并在我的 views.py 中进行了设置,但是我收到了这个错误,我不知道为什么?
views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
class MailSender():
host = settings.EMAIL_HOST_USER
def sendMail(self, formData, message, sender):
return send_mail(formData, message, self.host, sender, fail_silently = False)
class ContactMe(View):
template = "contact.html"
context =
'form': ContactForm()
def get(self, request):
print("getting form")
return render(request, self.template, self.context)
def post(self, request):
form = ContactForm(request.POST)
if form.is_valid():
data = form.cleaned_data
print(data)
mailSender(ContactForm, data['message'], settings.EMAIL_HOST_USER, ['myemail@email.com'])
MailSender.sendMail()
if emailsent == True:
returnData =
'success': True,
'message': 'Email not sent, but data received'
else:
returnData =
'success': True,
'message': 'Email not sent, but data received'
# return JsonResponse(returnData, safe=False)
next = request.POST.get('next', '/')
return HttpResponseRedirect(next)
def post_regularDjango(self, request):
form = ContactForm(request.POST)
if form.is_valid():
data = form.cleaned_data
print(data['from_email'], data['subject'], data['subject'])
return render(request, self.template, self.context)
else:
print("form invalid")
self.context.form = form
return render(request, self.template, self.context)
settings.py 文件中的电子邮件设置
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail@email.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
任何帮助将不胜感激。
亲切的问候,
【问题讨论】:
在views.py中显示使用的导入 @iklinac 哈哈,抱歉我忘了补充。我已经更新了帖子,你可以在 view.py 部分看到导入 这能回答你的问题吗? How do I reference a Django settings variable in my models.py? 【参考方案1】:你还没有将 Django settings 导入到 views.py 中
from django.conf import settings
【讨论】:
哈哈,现在觉得自己傻了!我想我在测试和尝试不同方法时不小心删除了。以上是关于Django联系表格邮件发送[重复]的主要内容,如果未能解决你的问题,请参考以下文章