我正在尝试在Django中创建一个真正发送电子邮件的联系表单。我能否将所有电子邮件配置放在views.py文件中?我想这样做是因为我希望只有合法的邮件所有者才能真正发送邮件。我不希望别人使用他们朋友的电子邮件给我发送邮件。
我正在尝试在Django中创建一个真正发送电子邮件的联系表单。我能否将所有电子邮件配置放在views.py文件中?我想这样做是因为我希望只有合法的邮件所有者才能真正发送邮件。我不希望别人使用他们朋友的电子邮件给我发送邮件。
当然可以,但请确保你的电子邮件凭据已安全存储在settings.py
文件中。
理想情况是将电子邮件凭据保存为环境变量,放在您的settings.py
文件中。
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = "from@example.com"
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# If you are using any other smtp host.
# Search documentation for other smtp host name and port number
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = "from@example.com"
EMAIL_HOST_PASSWORD = "SUPER_SECRET_PASSWORD"
您希望使用的视图来发送电子邮件views.py
from django.core.mail import EmailMessage
def email_send_view(request):
if request.method == "POST":
# Get email information via post request
to_email = request.POST.get("to", "")
subject = request.POST.get("subject", "")
message = request.POST.get("message", "")
if to_email and message:
email = EmailMessage(subject=subject,body=body,to=[to])
email.send()
# Complete your view
# ...
return redirect("REDIRECT_VIEW")
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from YourProject.settings import EMAIL_HOST_USER
def email_send_view(request):
if request.method == "POST":
# Get email information via post request
to_email = request.POST.get("to", "")
subject = request.POST.get("subject", "")
message = request.POST.get("message", "")
if to_email and message:
# Gets HTML from template
# Make sure in this case you have
# html template saved in your template directory
html_message = render_to_string('template.html',
{'context': 'Special Message'})
# Creates HTML Email
email = EmailMultiAlternatives(subject,
from_email=EMAIL_HOST_USER,
to=[to])
# Send Email
email.attach_alternative(html_message, "text/html")
email.send()
# Complete your view
# ...
return redirect("REDIRECT_VIEW")