Although Python provides a mail sending interface via the
smtplib module, Django provides a couple of light wrappers over it. we will see how to implement mailing function in Django to send a mail to the user from a web application.
The code lives in the
from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'email@example.com', ['firstname.lastname@example.org'], fail_silently=False, )
This function will not work as of now . we need to do little configurations to make this piece of code to work
Code need to add into the setting.py file in your django project
EAMIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email@example.com' EMAIL_HOST_PASSWORD = 'yourpassword' EMAIL_USE_TLS = True
Now we will understand the actual function
from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect def send_email(request): subject = request.POST.get('subject', '') message = request.POST.get('message', '') from_email = request.POST.get('from_email', '') if subject and message and from_email: try: send_mail(subject, message, from_email, ['firstname.lastname@example.org']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: # In reality we'd use a form class # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.')
Now we will disscuss the every part of the code so that u will get to know about each and every piece
subject is a string. which you can include the alphabetical charecters
message is a string. which you can include the Message to the user in charecters of alphabeticals
A string. If
None, Django will use the value of the
A list of strings, each an email address. Each member of
recipient_list will see the other recipients in the “To:” field of the email message.
The optional username to use to authenticate to the SMTP server. If this isn’t provided, Django will use the value of the
The optional password to use to authenticate to the SMTP server. If this isn’t provided, Django will use the value of the
The optional email backend to use to send the mail. If unspecified, an instance of the default backend will be used. See the documentation on Email backends for more details.
html_message is provided, the resulting email will be a multipart/alternative email with
message as the text/plain content type and
html_message as the text/html content type.
Yes we can the mails to the user with django framework easily and needs little effort of configuring the settings file in the project.there is also an option to send mass emails with the django that will the our next article.
# DjangoDocumentation : https://docs.djangoproject.com/en/3.1/topics/email/
# DjangostaanInstagram : https://www.instagram.com/djangostaan/
follow us for more Updates on django framework ………Share this article to give us little inspiration