SMTP issue in Django web application - python

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 :)

Related

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.

Using Outlook SMTP server to send email through a contact form but unable to send as I need the server to be able to accept multiple "From" addresses

Currently using Django as the chosen framework for my project and I have implemented a contact form and my main goal is for users to complete the contact form and the admin of the site (me) get an email, which shows me the details of their enquiry.
I am trying to use the Outlook SMTP server and these are my current settings in settings.py:
EMAIL_HOST = 'smtp.office365.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '<my_emailAddress>'
EMAIL_HOST_PASSWORD = os.environ.get('OUTLOOK_PASSWORD')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = '<my_emailAddress>'
However, whenever I complete the form and send the request to the server I am receiving the following error code:
(554, b'5.2.252 SendAsDenied; <my_emailAddress> not allowed to send as <inputtedForm_emailAddress>; STOREDRV.Submission.Exception:
SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message.
I am looking for some help surrounding this issue - it would be greatly appreciated.
Recently I had same issue with Outlook.
Looks like Outlook is not accepting anymore sending emails from unsecure apps.
Your next alternative is to use gmail but first enable unsecure apps in gmail setting.
Everything should be the same, change only smtp to
​EMAIL_HOST=smtp.gmail.com

Django not sending email through gmail

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

Python Django Gmail SMTP setup

I am trying to send email from Django by setting up gmail smtp.
But everytime it is returning me 0 status. I have searched different relevant answers in stackoverflow and i am setting up the smtp server the same way but still it is not sending any email..
Below is my setting file
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'my gmail account'
EMAIL_HOST_PASSWORD = 'my gmail account password'
DEFAULT_FROM_EMAIL = 'my gmail account'
DEFAULT_TO_EMAIL = 'to email'
Below is my code
from django.conf import settings
from django.core.mail import send_mail
print "Sending Email"
mail_title = 'Test Email'
message = 'This is a test email.'
email = settings.DEFAULT_FROM_EMAIL
recipients = [settings.DEFAULT_TO_EMAIL]
print send_mail(mail_title, message, email, recipients, settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
print "Email Sent"
But everytime it print status 0 which means email is not sent. About the environment i am running this code on Amazon EC2 instance which has ubuntu as an OS and Apache as server..
Do i need to do additional setups for sending email through gmail smtp??
Much appreciate your help
Thanks in advance
Your gmail.smtp setup is correct. It looks like you are not calling the send_email function correctly, and that's why it's not sending. In the python shell, try the following:
import django
from django.conf import settings
from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', settings.EMAIL_HOST_USER,
['to#example.com'], fail_silently=False)
Try to change EMAIL_USE_TLS=True to EMAIL_USE_SSL=True and EMAIL_PORT=465
https://docs.djangoproject.com/en/1.10/topics/email/

send mail with Django using EmailMessage class

I am trying to send an email using the EmailMessage class provided by Django. My code in views.py is as follows:
email = EmailMessage('Hello', 'My_message ', 'my#mail.com', [email])
email.attach_file('file.jpg')
email.send()
I get an [Errno 111] Connection refused. What could be the source of this error? Are there any additional settings that I should be aware of when trying to send an email with an attachment in Django? Thanks a lot
[edit] I forgot to mention i am working on the development server provided by django
most likely, Django can't connect to a mail server on localhost. If you look here, look for EMAIL_HOST, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD
The easiest way to set the email for testing purposes in Django would be to set it to a gmail account with SMTP.
In settings.py just add this.
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'user#gmail.com'
EMAIL_HOST_PASSWORD = 'your-password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
For production you will need some sort of mail server installed on your server, or connect to a remote mail server.
Hope this helps in some way.
Like Chris Curvey mentioned, you'll have to configure your mail settings as is described here: http://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#available-settings
Which mail host to use depends on your connection. If you are at work, then there should be a system administrator who can tell you which information to use. If you're at your own home, then your ISP probably has a mail server that you're supposed to use.
If you have a functioning email client on your computer, then you should also be able to see the proper settings in "Outgoing Mail" or something to that effect.

Categories