我正试图在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")
如果您想通过django应用使用电子邮件Email Template
发送html template
或image
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")