Reputation: 25
I wrote a application to send a mail through django
models.py
from django.db import models
from django import forms
class EmailForm(forms.Form):
firstname = forms.CharField(max_length=255)
lastname = forms.CharField(max_length=255)
email = forms.EmailField()
subject = forms.CharField(max_length=255)
botcheck = forms.CharField(max_length=5)
message = forms.CharField()
views.py
from django.views.generic.base import TemplateView
from django.http import HttpResponseRedirect
from django.core.mail import send_mail, BadHeaderError
from models import EmailForm
from django.shortcuts import render
def sendmail(request):
if request.method == 'POST':
form = EmailForm(request.POST)
if form.is_valid():
firstname = form.cleaned_data['firstname']
lastname = form.cleaned_data['lastname']
email = form.cleaned_data['email']
subject = form.cleaned_data['subject']
botcheck = form.cleaned_data['botcheck'].lower()
message = form.cleaned_data['message']
if botcheck == 'yes':
try:
fullemail = firstname + " " + lastname + " " + "<" + email + ">"
send_mail(subject, message, email, ['[email protected]'], fail_silently=False)
return HttpResponseRedirect('/email/thankyou/')
except:
return HttpResponseRedirect('/email/')
else:
return HttpResponseRedirect('/email/')
else:
return HttpResponseRedirect('/email/')
when the
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
it displaying in the console.
but when the
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
it not sending the email to the specified user. my settings.py file
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'localhost'
EMAIL_PORT = '8000'
how I can send the email?
Upvotes: 2
Views: 1899
Reputation: 2213
You have specified your EMAIL HOST as localhost
change it to a reliable email host like gmail. Your settings.py can have the below given settings to send emails using gmail smtp server. You have to change the port too.
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'
If issues persists you have to allow less secure apps
to access your gmail account. This is a recent change that gmail made to their account access policies. By default only a qualified domain can send emails using gmail authentication (OAUTH2
) mechanism. To allow less secure apps to access your gmail account you have to sign in to google developer console.
Upvotes: 4