Django 1.8 sending mail using gmail SMTP - python

I was trying send a mail using smtp.gmail.com in django 1.8
My settings.py contains:
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=465
EMAIL_HOST_USER = 'sarath4coding'
EMAIL_HOST_PASSWORD = '*********'
DEFAULT_EMAIL_FROM = 'sarath4coding#gmail.com'
from django.core import mail
mail.send_mail('subject','message','sarath4coding#gmail.com',['sarath4coding#gmail.com'])
But got this error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/manager/dj1.8/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
File "/home/manager/dj1.8/local/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/manager/dj1.8/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages
new_conn_created = self.open()
File "/home/manager/dj1.8/local/lib/python2.7/site-packages/django_smtp_ssl.py", line 14, in open
self.connection.login(self.username, self.password)
File "/usr/lib/python2.7/smtplib.py", line 622, in login
raise SMTPAuthenticationError(code, resp)
SMTPAuthenticationError: (534, '5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbuze\n5.7.14 2FDKQt2Dlo2vqFIvbr6DnBItwWvh9DChPwbeTZO66N91gzmiA437Vqs80cZ9-8u13vxq5a\n5.7.14 bVahzO_BQcZ53yKbJ-YbAlmFE1XIK7MfH97O0wI1lvzpTG_WAHuTIBF0HD1GA2icUoUemt\n5.7.14 ErZn4qb942aAIMG103FnrzLp4txXTbXC-wGLpaz5yvnUN5thahvv3-RiIVW8F1QddZKZlg\n5.7.14 qQKpqWw56zr1AcO2s_oaBEt556fQ> 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 kx14sm6579665pab.0 - gsmtp')
I tried everything the document says and followed many suggested solutions.
like https://accounts.google.com/DisplayUnlockCaptcha, enabling low security apps etc.
but I still got errors
Can anybody tell how to properly configure Django 1.8 to send mail using Gmail.

for me in settings.py:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'test#gmail.com'
EMAIL_HOST_PASSWORD = 'test'
EMAIL_PORT = 587
and views.py:
from django.core.mail import EmailMessage
email = EmailMessage('title', 'body', to=[email])
email.send()
and: https://accounts.google.com/DisplayUnlockCaptcha
and also make sure you turn on permission for less secure apps.

Remember to:
Go to your Google Account settings, find Security -> Account permissions -> Access for less secure apps, enable this option.
About this option: https://support.google.com/accounts/answer/6010255

I tested this and worked perfect in django 1.8:
first you should check this link, provided by google which you did :)
notice that for some strange reasons that I don't know,you have to code like this in view.py or shell:
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)
also this is my settings in setting.py file:
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = 'xxxx' #my gmail password
EMAIL_HOST_USER = 'xxxx#gmail.com' #my gmail username
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

replace in your settings.py file :
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
by
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

In settings.py
change this
EMAIL_HOST='imap.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'yadavabhishek260#gmail.com'
EMAIL_HOST_PASSWORD ='**********'
EMAIL_USE_SSL=False
EMAIL_USE_TLS= True

This works for me:
settings.py
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = 'test'
EMAIL_HOST_USER = 'test#gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
Unlock Captcha: https://accounts.google.com/DisplayUnlockCaptcha
views.py
email = EmailMessage(
'subject_message',
'content_message',
'sender smtp gmail' +'<sender#gmail.com>',
['receiver#gmail.com'],
headers = {'Reply-To': 'contact_email#gmail.com' }
)
email.send()

I used this for django 1.11
In settings.py
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = 'sender' #sender mail password
EMAIL_HOST_USER = 'sender#mail.com' #sender mail username
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
In view.py
send_mail('mail subject', 'body content',settings.EMAIL_HOST_USER,
['receiver#mail.com'], fail_silently=False)
and goto https://myaccount.google.com/u/0/security?hl=en to enable Less secure app access

Related

Djnago send mail not working, also not showing any error

Settings.py
DEFAULT_FROM_EMAIL = 'testing.email2908#gmail.com'
SERVER_EMAIL = 'testing.email2908#gmail.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'testing.email2908#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAILL_USE_TLS = True
views.py
print('Helloo')
send_mail(
'Testing',
'Hi',
'testing.email2908#gmail.com',
['xyz#gmail.com'], #my personal gmail id
fail_silently=False,
)
print('Hiiii')
When i run this code, only Helloo is getting printed, I've imported send_mail as well,tried using smtplib as well but that was giving smpt auth extension error so i'm trying send_mail method but it also doesn't seem to work, don't know what is the exact issue.
try this
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'emailId'
EMAIL_HOST_PASSWORD = 'password'
Need to set Following configuration in settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'xyz.gmail.com' # sender's email-id
EMAIL_HOST_PASSWORD = 'xyz' # password associated with above email-id
I think you forgot EMAIL_BACKEND.
To send mail add following code
from django.conf import settings
from django.core.mail import send_mail
subject = 'email subject'
message = 'Hi , Thank you for your help.'
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email, ] # email to send
send_mail( subject, message, email_from, recipient_list )
If you are using gmail for sending mails then you need to turn on Less Secure App Access. The option is present in Manage Your Account in gmail.
I hope it will help you.

Django is not sending mail

We have a Django application that runs on CentOS.
We've created a new feature for password reset using the Django auth and forms.
This works when working on development servers but when I deploy this to our production environment the mail with the unique link is not being sent.
I've pinpointed the problem to the fact that Django using smtplib is trying to send the e-mail through port 25 with Postfix instead using the settings.py which is pointed to Google server.
When i turn Postfix off I get connection refused when trying to reset the password.
We have other mail functionality that works, only the reset password doesn't.
My settings.py:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'my-mail#gmail.com'
EMAIL_HOST_PASSWORD = 'my-pass'
DEFAULT_FROM_EMAIL = 'my-mail#gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
SERVER_EMAIL = 'my-mail#gmail.com'
The view is from auth_views.password_reset and I'm calling it from my main urls.py file.
Solution:
It turns out I had another settings.py file located in the home directory of the project as backup.
The problem was I added this home directory in the apache/django.wsgi file so Django was looking at this file and not the updated.
Once I've deleted this file everything works.
Thanks for your help.
Solution: It turns out I had another settings.py file located in the home directory of the project as backup. The problem was I added this home directory in the apache/django.wsgi file so Django was looking at this file and not the updated. Once I've deleted this file everything works. Thanks for your help.
I have simply set following setting:
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'myemailpwd'
And, following code send emails without any interruption
from django.core.mail import EmailMessage
email = EmailMessage('TEST TITLE', 'TEST BODY', to=[email])
email.send()
Try below code and write error you are getting if any.
In settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'your email'
EMAIL_HOST_PASSWORD = 'your password'
EMAIL_PORT = 587
In send_mail.py
from django.core.mail import EmailMultiAlternatives
import settings
def send_mail():
from_email = settings.EMAIL_HOST_USER
to_email = ['your_email_address#example.com']
subject = "Any text"
body = "Hello world"
msg = EmailMultiAlternatives(subject, body, from_email, to_email)
msg.send()
send_mail()

django's email library not working on heroku

I am using djangos's send_email function for sending emails to users. Below are my settings.
from django.core.mail import send_mail
EMAIL_HOST_USER = 'mymail#gmail.com'
EMAIL_HOST_PASSWORD='password+'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
This is working fine on local this error env but not on heroku.
It is showing:
SMTPAuthenticationError

Cannot able to send Email on Django 1.10?

I am facing a problem on sending mail on Django version 1.10 and the following erron can be appear in my console.
Error
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
gaierror: [Errno -2] Name or service not known
My code is,
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'mymail#gmail.com'
EMAIL_HOST_PASSWORD = '************'
DEFAULT_EMAIL_FROM = 'mymail#gmail.com'
EMAIL_USE_TLS = True
views.py
from django.shortcuts import render
from django.core.mail import EmailMessage
from django.core.mail import send_mail
def contact(request):
if request.method == 'POST':
print "----------------"
email = EmailMessage('title', 'body', to=['mymail#gmail.com'])
email.send()
print"--------------------stop"
return render(request, 'contact/contact.html')
return render(request, 'contact/contact.html')
Have you enabled Access for less secure apps? If not then,
Go to your Google Account settings, find Security -> Account permissions -> Access for less secure apps, enable this option.
https://accounts.google.com/b/0/DisplayUnlockCaptcha
Try this:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'e-mail#gmail.com'
EMAIL_HOST_PASSWORD = '*******'
EMAIL_USE_SSL = True
And and I would add this:
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
The latter will use the terminal to show your e-mails in text.
If you do not want to use the terminal to see your e-mails, rather send real e-mails, remove the EMAIL_BACKEND variable from your Settings.py.
I think you have:
DEFAULT_EMAIL_FROM = 'mymail#gmail.com'
instead:
DEFAULT_FROM_EMAIL = 'mymail#gmail.com'

How to send email via Django?

In my settings.py, I have the following:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Host for sending e-mail.
EMAIL_HOST = 'localhost'
# Port for sending e-mail.
EMAIL_PORT = 1025
# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
My email code:
from django.core.mail import EmailMessage
email = EmailMessage('Hello', 'World', to=['user#gmail.com'])
email.send()
Of course, if I setup a debugging server via python -m smtpd -n -c DebuggingServer localhost:1025, I can see the email in my terminal.
However, how do I actually send the email not to the debugging server but to user#gmail.com?
After reading your answers, let me get something straight:
Can't you use localhost(simple ubuntu pc) to send e-mails?
I thought in django 1.3 send_mail() is somewhat deprecated and EmailMessage.send() is used instead?
I use Gmail as my SMTP server for Django. Much easier than dealing with postfix or whatever other server. I'm not in the business of managing email servers.
In settings.py:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'me#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
NOTE: In 2016 Gmail is not allowing this anymore by default. You can either use an external service like Sendgrid, or you can follow this tutorial from Google to reduce security but allow this option: https://support.google.com/accounts/answer/6010255
Send the email to a real SMTP server. If you don't want to set up your own then you can find companies that will run one for you, such as Google themselves.
Create a project: django-admin.py startproject gmail
Edit settings.py with code below:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'youremail#gmail.com'
EMAIL_HOST_PASSWORD = 'email_password'
EMAIL_PORT = 587
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=['your#email.com'])
email.send()
For more informations, check send_mail and EmailMessage features in documents.
UPDATE for Gmail
Also if you have problems sending email via gmail remember to check this guides from google.
In your Google account settings, go to Security > Account permissions > Access for less secure apps and enable this option.
Also create an App specific password for your gmail after you've turned on 2-step-verification for it.
Then you should use app specific password in settings. So change the following line:
EMAIL_HOST_PASSWORD = 'your_email_app_specific_password'
Also if you're interested to send HTML email, check this out.
My site is hosted on Godaddy and I have a private email registered on the same.
These are the settings which worked for me:
In settings.py:
EMAIL_HOST = 'mail.domain.com'
EMAIL_HOST_USER = 'abc#domain.com'
EMAIL_HOST_PASSWORD = 'abcdef'
DEFAULT_FROM_EMAIL = 'abc#domain.com'
SERVER_EMAIL = 'abc#domain.com'
EMAIL_PORT = 25
EMAIL_USE_TLS = False
In shell:
from django.core.mail import EmailMessage
email = EmailMessage('Subject', 'Body', to=['def#domain.com'])
email.send()
Then I got "1" as the O/P i.e. Success. And I received the mail too. :)
What is the meaning of domain.com?
For Django version 1.7, if above solutions dont work then try the following
in settings.py add
#For email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'sender#gmail.com'
#Must generate specific password for your app in [gmail settings][1]
EMAIL_HOST_PASSWORD = 'app_specific_password'
EMAIL_PORT = 587
#This did the trick
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
The last line did the trick for django 1.7
You need to use smtp as backend in settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
If you use backend as console, you will receive output in console
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
And also below settings in addition
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'urusername#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
If you are using gmail for this, setup 2-step verification and Application specific password and copy and paste that password in above EMAIL_HOST_PASSWORD value.
I found using SendGrid to be the easiest way to set up sending email with Django. Here's how it works:
Create a SendGrid account (and verify your email)
Add the following to your settings.py:
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = '<your sendgrid username>'
EMAIL_HOST_PASSWORD = '<your sendgrid password>'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
And you're all set!
To send email:
from django.core.mail import send_mail
send_mail('<Your subject>', '<Your message>', 'from#example.com', ['to#example.com'])
If you want Django to email you whenever there's a 500 internal server error, add the following to your settings.py:
DEFAULT_FROM_EMAIL = 'your.email#example.com'
ADMINS = [('<Your name>', 'your.email#example.com')]
Sending email with SendGrid is free up to 12k emails per month.
I had actually done this from Django a while back. Open up a legitimate GMail account & enter the credentials here. Here's my code -
from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
def sendmail(to, subject, text, attach=[], mtype='html'):
ok = True
gmail_user = settings.EMAIL_HOST_USER
gmail_pwd = settings.EMAIL_HOST_PASSWORD
msg = MIMEMultipart('alternative')
msg['From'] = gmail_user
msg['To'] = to
msg['Cc'] = 'you#gmail.com'
msg['Subject'] = subject
msg.attach(MIMEText(text, mtype))
for a in attach:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(a))
msg.attach(part)
try:
mailServer = smtplib.SMTP("smtp.gmail.com", 687)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, [to,msg['Cc']], msg.as_string())
mailServer.close()
except:
ok = False
return ok
You could use "Test Mail Server Tool" to test email sending on your machine or localhost. Google and Download "Test Mail Server Tool" and set it up.
Then in your settings.py:
EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
From shell:
from django.core.mail import send_mail
send_mail('subject','message','sender email',['receipient email'], fail_silently=False)
Late, but:
In addition to the DEFAULT_FROM_EMAIL fix others have mentioned, and allowing less-secure apps to access the account, I had to navigate to https://accounts.google.com/DisplayUnlockCaptcha while signed in as the account in question to get Django to finally authenticate.
I went to that URL through a SSH tunnel to the web server to make sure the IP address was the same; I'm not totally sure if that's necessary but it can't hurt. You can do that like so: ssh -D 8080 -fN <username>#<host>, then set your web browser to use localhost:8080 as a SOCKS proxy.
For SendGrid - Django Specifically:
SendGrid Django Docs here
Set these variables in
settings.py
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'sendgrid_username'
EMAIL_HOST_PASSWORD = 'sendgrid_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
in views.py
from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', 'from#example.com', ['to#example.com'], fail_silently=False)
below formate worked for me
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True EMAIL_HOST = 'mail.xxxxxxx.xxx'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'support#xxxxx.xxx'
EMAIL_HOST_PASSWORD = 'xxxxxxx'
In settings.py configure the email as following
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'user#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
In most of the cases Gmail settings is missed out. Make sure that the less secure app access is turned on. You can also check the procedure here
Then send email within views
from django.core.mail import send_mail
def send(request):
send_mail(
‘Email Subject here’,
‘Email content’,
settings.EMAIL_HOST_USER,
[‘emailto#gmail.com’],
fail_silently=False)

Categories

Resources