How to send email on form submission using django forms?

牧云@^-^@ 提交于 2019-12-11 10:18:10

问题


Prior to sending mails on actual website, I'm running a small test Django local SMTP server: I have to congifure these settings in settings.py. But where do I put it?

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = '1025'
EMAIL_USE_TLS = True

Then how do I proceed? Please help.


回答1:


You need to put these in your settings.py file. You can put the below settings anywhere in your settings.py file.

settings.py

...

EMAIL_HOST = 'smtp.gmail.com'  # since you are using a gmail account
EMAIL_PORT = 587  # Gmail SMTP port for TLS
EMAIL_USE_TLS = True    
...

local_settings.py

EMAIL_HOST_USER = 'your_username@gmail.com'
EMAIL_HOST_PASSWORD = 'your_gmail_password'

Then to send an email, you can use Django's send_email().

from django.core.mail import send_mail

send_mail('My Subject', 'My message', 'from@example.com',
    ['to@example.com'], fail_silently=False)

Mail is then sent using the SMTP host and port specified in the EMAIL_HOST and EMAIL_PORT settings in your settings.py file. The EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings, if set, are used to authenticate to the SMTP server, and the EMAIL_USE_TLS settings control whether a secure connection is used.

Signature of send_email():

send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)

Note: You can put your gmail account information in a local_settings.py and add this local_settings to git-ignore. Then include this local_settings in your settings.py. This way only you would be able to see your local_settings.



来源:https://stackoverflow.com/questions/31334029/how-to-send-email-on-form-submission-using-django-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!