There are actually 2 steps involve with sending emails in Django.
open your Django application settings.py file and configure the Email settings in accordance with your mail carrier. In our case, we will be using gmail.
| EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = "587"
EMAIL_HOST_USER = "[YOUR_HOST_EMAIL]"
EMAIL_HOST_PASSWORD = "[EMAIL_HOST_PASSWORD]" # https://support.google.com/mail/answer/7126229?hl=en
EMAIL_USE_TLS = True # Yes for Gmail
|
That's pretty much what we need at this point to get our email going.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | def sendemail(name, phone, subject, email, message, receivers):
from django.conf import settings
from django.core.mail import send_mail
from django.template import loader
"""
Send email from contact form
"""
recipient_list = [email_tuple[1] for email_tuple in receivers]
subject = 'New contact message on Otcollect'
html_message = loader.render_to_string(
'contact_email.html',
{
'name': name,
'email': email,
'subject': subject,
'phone': phone,
'message': message
}
)
send_mail(subject, message, email, recipient_list, fail_silently=True, html_message=html_message)
|
My contact_email.html is very simple:
1
2
3
4
5
6
7
8
9
10
11
12 | <!--html-->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>{{ name }}</h1>
<h2>{{ subject }}</h2>
<p>{{ phone }}-{{ email }}</p>
<p>{{ message }}</p>
</body>
</html>
|