

How to send e-mail in django ?
source link: https://dev.to/yash2115/how-to-send-e-mail-in-django-37ge
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In django we can send e-mail using SMTP (Simple Mail Transfer Protocol) service which is inbuilt package in python and also in django.
What is smtp ?
SMTP (Simple Mail Transfer Protocol) is service that provides service to send, receive, and or relay outgoing mail between senders and receivers.
SMTP service takes your client email address(you can also give multiple email address) which you are using and it is formatted as smtp.gmail.com because let's take and example Gmail’s SMTP server address is smtp.gmail.com, and Twilio Send Grids is smtp.sendgrid.com. You can generally find your SMTP server address in the account or settings section of your mail client.
Django email sending setup
Step 1 --> create one folder and name it as django_email
Step 2 --> Create django project using below command django-admin startproject emails .
Directory preview
Step 3 --> Create django app in project created from above step and use command python manage.py startapp main
Directory preview
Step 4 --> Now install app in settings.py and this file will be in emails folder
Directory preview
Step 5 --> Now you need to migrate the project using command python manage.py migrate
Step 6 --> Go in settings.py and go at the bottom and write code under static variable
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'gmail account email id'
EMAIL_HOST_PASSWORD = 'Your gmail password'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
Here in variable EMAIL_HOST_USER
you need to write the email id which have two step verification off because we need to make some settings change on your g-mail account. And In variable EMAIL_HOST_PASSWORD
you need you write your g-mail account password.
Step 7 --> Now open your favorite browser and follow below steps
Go in option Account
Go in option Security and search for Less secure app access and turn that on because if you will not turn that on then django will not able to send the mail.
Directory preview
Step 8 --> Now create form.py file in mail folder and write code below code
form.py
from django import forms
class ContactMeForm(forms.Form):
first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter first name'}), required=True)
last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter last name'}), required=True)
emailid = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter email id'}), required=True)
phone_number = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter phone number'}))
subject = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter subject'}), required=True)
message = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'placeholder':'Enter Message'}), required=True)
Step 9 --> Now go in views.py file and write below code
views.py
from django.shortcuts import render
from main.form import ContactMeForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.contrib import messages
def home(request):
form = ContactMeForm()
if request.method == 'POST':
form = ContactMeForm(request.POST)
if form.is_valid():
# form.save()
# send_mail(subject, message[fname, lname, email, phonenumber, subject, message], sedner, recipient)
subject = "Contact form inquiry"
body = {
'first_name': form.cleaned_data['first_name'],
'last_name':form.cleaned_data['last_name'],
'email': form.cleaned_data['emailid'],
'phonenumber': form.cleaned_data['phone_number'],
'subject': form.cleaned_data['subject'],
'message': form.cleaned_data['message'],
}
message = '\n'.join(body.values())
sender = form.cleaned_data['emailid']
recipient = ['[email protected]']
try:
send_mail(subject, message, sender, recipient, fail_silently=True)
except BadHeaderError:
return HttpResponse("Invalid header found.")
messages.success(request, "Your respoce has been submited successfully")
context = {
'form':form,
}
return render(request, "home/index.html", context)
Step 10 --> Now create urls.py file in main folder
Directory preview
Step 11 --> Open urls.py created in main folder and write below code
from django.urls import path
from main import views
urlpatterns = [
path('', views.home, name="home"),
]
Step 12 --> Now register urls.py created in main folder to emails>url.py as shown below
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls'))
]
Step 13 --> Now create templates folder in main folder and create home folder in templates folder and create index.html in home folder
SOME THING LIKE THIS main>templates>home>index.html
Directory preview
Step 14 --> Open index.html and write below code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<style>
.marg {
margin: 20%;
}
</style>
</head>
<body>
<dev class="marg">
<form class="form-contact contact_form container" action="{% url 'home' %}" method="post" id="contactForm"
novalidate="novalidate">
<h1>Contact us form</h1>
{% csrf_token %}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="first_name">Enter first name</label>
{{ form.first_name }}
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="last_name">Enter last name</label>
{{ form.last_name }}
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="email">Enter Email id</label>
{{ form.emailid }}
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="phone_number">Enter phone number</label>
{{form.phone_number}}
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="subject">Subject</label>
{{form.subject}}
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="Message">Enter Message</label>
{{form.message}}
</div>
</div>
</div>
<div class="form-group mt-lg-3">
<button type="submit" class="btn btn-outline-success">Send Message</button>
</div>
</form>
</dev>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"
crossorigin="anonymous"></script>
</body>
</html>
Step 15 --> Now start your django server using command python manage.py runserver
**Step 16 --> Fill the data and click on submit button and see your mail mail box you must see mail
mail received
If you like this shot django mail sending tutorial then please like this blog and if you have any doubts the let me know in discussion box
Recommend
-
20
Send mail with a BASH Shell Script Posted: 2007-06-10 - Last updated: 2019-06-05 Tagged
-
7
Unable to send mail iPhone SE S Cee macrumors member Original poster
-
12
How to send an 'E mail' - Database - 19845,790,971 views•Feb 26, 2016 ...
-
16
Unable to send e-mail to laravel 5.2 advertisements I am trying to send an email with laravel 5.2 . This is my first time of sending email in...
-
16
How do I send PHP mail via SMTP? Overview When you use the PHP mail function, you are sending...
-
29
Php contact form does not send e-mail advertisements This question already has an answer here: PHP mail function doesn't complete...
-
5
Phpmailer to send e-mail from any gmail advertisements I used the following code snippet using phpmailer class inorder to send an email using gmail...
-
8
What have people used for an E-mail send relay? Floodgap may be relocating, which may mean if I can’t preserve the IP that I’d lose over a decade of accumulated good karma (I do have an SPF and have never been on any majo...
-
11
Send an e-mail from a script in batches. Blat does not work advertisements I need to send an email from a batch script. I tried several soluti...
-
5
Laravel 7 Send Mail Using Markdown Example 8646 views 1 year ago Laravel Today, markdown laravel 7 mail i...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK