Django not sending email through gmail - python

I am trying to build a online book store and I am trying to send an verification email to new signed users, but for some reason Email is not getting sent, I also tried to use app specific password in gmail.
A help will be greatly appreciated.
Here is my Email code in settings.py
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='kshitu.rangari#gmail.com'
EMAIL_HOST_PASSWORD='jgpcjiajvklxraof'
EMAIL_PORT=587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'books#pickabook.com'
Code in my Views.py
from .models import Book
def index (request):
return render (request,'template.html')
def store (request):
return render (request, 'store.html' )
def store (request):
count = Book.objects.all().count()
context = {
'count':count,
}
return render (request,'store.html',context)

As you already have the settings for email ready and to test whether emails are being sent, do the following
In settings.py make
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
Run interactive mode,
python manage.py shell
Import the EmailMessage module,
from django.core.mail import EmailMessage
Send the email,
email = EmailMessage('Subject', 'Body', to=['kshitu.rangari#gmail.com'])
email.send()
If the above works successfully then your gmail account is configured to send emails.

For Gmail specifically, you might need to toggle the "enable less secure apps" function within your Google account.
https://support.google.com/accounts/answer/6010255?hl=en

Related

"Relay access denied" in django app using namecheap private email

So I have a Django app that sends confirmation emails to users who want to register their account. It looks something like this
views.py
def send_activation_email(user, request):
current_site = get_current_site(request)
email_subject = "Activation Email"
context = {"user": user,
"domain": current_site,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': generate_token.make_token(user)
}
email_body = render_to_string('email/activate.html',context)
email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email])
email.send()
and with settings.py looking like this
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'mail.privateemail.com'
EMAIL_FROM_USER = 'verification#ianisdo.xyz'
EMAIL_HOST_PASSWORD = '[redacted]'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
The problem is that, when I try to send a email when the user creates an account, I get this error
SMTPRecipientsRefused at /register/
{'ianis.donica#gmail.com': (554, b'5.7.1 <ianis.donica#gmail.com>: Relay access denied')}
What I know for sure is:
that it's not a problem with the private namecheap email, from which
I can still send emails just not from my website.
I also know the problem is not due to gmail not liking my email, as
the same error when the email is sent to a yahoo.com domain.
I also know that the issue is not with the settings.py not connecting
to the views.py
I also know that all the details are entered correctly
From my knowledge and talking to namecheap support, the issue is most likely caused by the header of the email but to my knowledge I can't seem to find anything wrong with it.
If someone is able to help me out, I would really appreciate it. I have had issues sending emails for about 9 days now
I think you need to add a value for EMAIL_HOST_USER in your settings.py. Without it, Django won't attempt to authenticate. Here's the relevant bit from the docs:
EMAIL_HOST_USER
Default: '' (Empty string)
Username to use for the SMTP server defined in EMAIL_HOST. If empty, Django won’t attempt authentication.
The username should match the password setting you're already providing (i.e., a valid namecheap private email account).

Can i use the views.py file to actually send emails?

I am trying to create a contact form in Django that actually sends emails for real. Can i put all the email configs in the views.py file itself? I want to do that because i want only the legitimate owners of emails to actually send emails. I do not people to send me emails using their friends email.
Yes obviously you can, but make sure you have your email credentials stored in your settings.py file safely
What is ideal is to save your email credentials as environment variables
In your settings.py File
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = "from#example.com"
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# If you are using any other smtp host.
# Search documentation for other smtp host name and port number
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = "from#example.com"
EMAIL_HOST_PASSWORD = "SUPER_SECRET_PASSWORD"
In your view that you want to use to send email
views.py
from django.core.mail import EmailMessage
def email_send_view(request):
if request.method == "POST":
# Get email information via post request
to_email = request.POST.get("to", "")
subject = request.POST.get("subject", "")
message = request.POST.get("message", "")
if to_email and message:
email = EmailMessage(subject=subject,body=body,to=[to])
email.send()
# Complete your view
# ...
return redirect("REDIRECT_VIEW")
If you want to send html template or image using email Email Template via your django app
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from YourProject.settings import EMAIL_HOST_USER
def email_send_view(request):
if request.method == "POST":
# Get email information via post request
to_email = request.POST.get("to", "")
subject = request.POST.get("subject", "")
message = request.POST.get("message", "")
if to_email and message:
# Gets HTML from template
# Make sure in this case you have
# html template saved in your template directory
html_message = render_to_string('template.html',
{'context': 'Special Message'})
# Creates HTML Email
email = EmailMultiAlternatives(subject,
from_email=EMAIL_HOST_USER,
to=[to])
# Send Email
email.attach_alternative(html_message, "text/html")
email.send()
# Complete your view
# ...
return redirect("REDIRECT_VIEW")

Using Sendgrid and Azure : 550, b'Unauthenticated senders not allowed'

I am trying to send a password reset email to users, via an App we are developping with Django.
When trying the App locally, the user can select to reset a pwd if forgotten , input his email into a field and submit, in order to receive an email. The sender email is a business email address.
Checking into Sendgrid, I can see the activity log that the email has been processed and delivered. So it seems working.
However, when trying to do the same passing via Github, Azure, on https://XXXXXX.azurewebsites.net/en/password_reset/, I get the following :
SMTPSenderRefused at /en/password_reset/
(550, b'Unauthenticated senders not allowed', 'nicolas#XXXXX.com')
in the log I get the following as well:
raise SMTPSenderRefused(code, resp, from_addr)
Is there something I am missing with Azure, another key to include. I read through many similar issues, but could not find a suitable response to my problem. The fact Sendgrid works locally but not with Azure make me think I am missing a connection at that level. Otherwise, All other aspects of the App works when hosting it on Azure..
Below are the codes I am using:
in settings.py
import os
ALLOWED_HOSTS = ['XXXXXX.azurewebsites.net']
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' #Exactly that
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'nicolas#XXXXX.com'
in views :
from django.core import mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
def send_password_reset_email(request):
subject = 'email reset'
html_message = render_to_string('password_reset_email.html', {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'nicolas#XXXXX.com'
form = (request.POST)
if form.is_valid():
data = form.cleaned_data
to=data.get("email")
mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message,fail_silently=False)
in url.py:
urlpatterns=[
url('', views.send_password_reset_email)
]
merci
Nicolas
This is solved: If SendGrid works locally, but not on Azure:
In Azure, select ‘configuration', 'Application settings', 'new application settings' and then, as per below, using the correct API name made it work.
In SendGrid, I had named my API key ‘test’, and thought in Azure I should name it the same. However, I should have named it the same as in my code:
SENDGRID_API_KEY
Not obvious at first.

SMTP issue in Django web application

I'm asked to add a feature to an existing program which is implemented using the Django/Python framework. This feature will allow the user to click on a button which it will show a small dialog/form to enter a value.
I did write some code which shows a message that the email is sent but in reality, it doesn't send it!
My code:
from django.shortcuts import render
from django.core.mail import send_mail
# Create your views here.
def index(request):
send_mail('Request for a Clause',
'This is an automated email. Jeff, please submit the case for 1234567',
'akohan#mycompay.com',
['jjohnson#mycompany.com'],
fail_silently=False)
return render(request, 'send/index.html')
In the project root, in the setting.py I have added SMTP configuration:
EMAIL_HOST = 'mail.mycompany.com'
EMIAL_PORT = 587
#EMAIL_HOST_USER = 'akohan#mycompany.com' ;no need it is on the white list
#EMAIL_HOST_PASSWORD = '' ;no need it is on the white list
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
I run it by typing:
python manage.py SendEmailApp
What am I missing here?
Personally, I have sent emails before in this way in a Django project and it worked great. You will have to allow SMTP access to your email.
import smtplib
def sendEmail():
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('yourEmailAddress#gmail.com', 'yourEmailPassword')
try:
server.sendmail('yourEmailAddress#gmail.com', 'emailAddressBeingSentTo', 'messageBeingSent')
except:
print('An error occurred when trying to send an email')
server.quit()
Side note. Security was not an issue for me so I did not check into it.
Hope this helps :)

In Django1.10, sending email functionality not working without any exception

I would like to send email in Django 1.10.
This is the snippet code in settings.py file.
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my email address'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
This is the snippet code in views.py file which is responsible for sending email.
from django.shortcuts import render
from django.core.mail import send_mail
from django.conf import settings
from .forms import contactForm
def contact(request):
form = contactForm(request.POST or None)
if form.is_valid():
name = form.cleaned_data['name']
comment = form.cleaned_data['comment']
subject = 'Message form MYSITE.com'
message = '%s %s' %(comment, name)
emailFrom = form.cleaned_data['email']
emailTo = [settings.EMAIL_HOST_USER]
send_mail(subject, message, emailFrom, emailTo, fail_silently=True)
context = locals()
template = "contact.html"
return render(request,template,context)
When I clicked submit button, I only received Review blocked sign-in attempt - google email.
So I have set my email account as Allow less secure apps: OFF.
Then hit the submit button again, I haven't received any email without any exception. As if sending email functionality working - browser loading for a little while.
I'm not sure why I couldn't receive email.
When I change fail_silently = False, I get a error like this.
SMTPAuthenticationError at /contact/
(534, '5.7.14 https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtS\n5.7.14 Mr_jh-DUic292PQTLx5X6kZmxxN8WFLelRksUwF0nHxSUPVpU_fX3m7ds3VOoUuTxL9Gya\n5.7.14 bqnAiUAIf2Er2n31EXEHIOpy2Kqn9cFH-PsIJSx1GBn_SxygkjHWgZ9KWc9cxIAKTGQtru\n5.7.14 O3QBqKb6vCyVHCiN8wUY6jAVRdoRg9aK9BL5GTo6QKUomIilah549hrwMgvMcYrrKCLMGI\n5.7.14 YuEWvMHHPdW6TXkBB75UP2wxRZ9fI> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 u2sm3991912edl.71 - gsmtp')
How can I handle it.

Categories