Here, we will explain how to send an email with Django. It can be used to create an inquiry form.
First, write the mail-related settings in settings.py
.
The following is an example when using Gmail.
settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD =Password for the app
EMAIL_PORT = 587
EMAIL_USE_TLS = True
Here, in the inquiry form
Define a function for sending mail in forms.py
.
forms.py
from django import forms
from django.conf import settings
from django.core.mail import BadHeaderError, EmailMessage
from django.http import HttpResponse
def send_email(self):
subject = 'Contact Us:' + self.cleaned_data['title']
name = self.cleaned_data['name']
email = self.cleaned_data['email']
from_email = '{name} <{email}>'.format(name=name, email=email)
message = self.cleaned_data['body']
recipient_list = [settings.EMAIL_HOST_USER]
email_message = EmailMessage(subject, message, from_email, recipient_list, reply_to=[email])
try:
email_message.send()
except BadHeaderError:
return HttpResponse('An invalid header has been detected.')
ʻIf you do not set reply_to
when creating an EmailMessage` instance, you will not be able to reply by email because you do not know the email address of the person who made the inquiry, so be sure to enter it.
Here, I explained the settings required when sending an email with Django. It can be applied to other than the inquiry form.
Recommended Posts