简体   繁体   中英

Can i use the views.py file to actually send emails?

I am trying to create a contact form in Django that actually sends emails for real. Can i put all the email configs in the views.py file itself? I want to do that because i want only the legitimate owners of emails to actually send emails. I do not people to send me emails using their friends email.

Yes obviously you can, but make sure you have your email credentials stored in your settings.py file safely What is ideal is to save your email credentials as environment variables In your settings.py File

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"

In your view that you want to use to send email 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")

If you want to send html template or image using email Email Template via your django app

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM