My code works and outputs the email to the console but I don't receive any email in my inbox.
My settings:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'youremail#gmail.com'
EMAIL_HOST_PASSWORD = 'yourpassword'
EMAIL_PORT = 587
First, you need to set EMAIL_BACKEND in setting like this.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Second, you need to define SMTP credentials details in settings.
For development on localhost, you can run local SMTP server by running following command on terminal.
python -m smtpd -n -c DebuggingServer localhost:1025
For more info Sending email
Add this in settings.py to print the email on console.
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Refer: Test sending email without email server
I'm new to Django, but I have read on the order of 50 pages (mostly SO and Django documentation) and haven't found anything that quite works for my situation.
I'm merely trying to send an email via the send_mail function in Django; although I'm hoping to get this working through SMTP on Gmail, right now it doesn't even work via localhost. When I run my test_email.py file where I'm testing this send_mail function, I get the following error:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
When I run this same send_mail call in the shell (via python manage.py shell), it's completely fine and displays the email just as I would expect. It's only once I try to run it in Django that the error pops up. Note that I get the above error no matter which permutation of the following 2 sets of settings I put in my settings.py file:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
I've also played around with the following in my settings.py file, and various mixes of these settings with the previous set (though I guess I'm getting ahead of myself seeing how localhost isn't working):
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myemail#gmail.com' # Note I'm using my actual gmail address here in real life
EMAIL_HOST_PASSWORD = '****' # Note I'm using my actual gmail password here in real life
DEFAULT_FROM_EMAIL = 'myemail#gmail.com' # Note I'm using my actual gmail address here in real life
SERVER_EMAIL = 'myemail#gmail.com' # Note I'm using my actual gmail address here in real life
I'm running the following command in a CMD prompt off to the side when I try to run going the localhost route:
python -m smtpd -n -c DebuggingServer localhost:1025
Here's the test_email.py file I'm trying to run in Django, where I get the connection refused error:
from django.core.mail import send_mail,EmailMessage
from django.conf import settings
settings.configure()
# Create your tests here.
# Email test #1: send email from my personal email to myself
send_mail(
'Email Test #1',
'Test if I can send email from my personal Gmail account to another email account via Django project.',
settings.EMAIL_HOST_USER,
['myemail#gmail.com'],
fail_silently=False
)
Any thoughts on why this isn't even working via localhost or suggestions on other things to try would be greatly appreciated.
Thanks!
I think there are some problem with gmail smtp service. Try using smtp service form sendgrid. It is also free for basic usage. I too was facing the same issue earlier.
In project settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'sendgridusername'
EMAIL_HOST_PASSWORD = 'sedgridpasseord'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'yourmail#site.com'
still error
Try if `smtp` service is working on your your server.
The following configuration worked for me:
settings.py
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = 'sendgrid-api-key' # this is your API key
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'your-email#example.com' # this is the sendgrid email
I used this configuration, and it worked properly, and I strongly suggest using environment variables to fill EMAIL_HOST_PASSWORD and DEFAULT_FROM_EMAIL:
import os # this should be at the top of the file
# ...
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "")
In order to send an email, use the following code:
from django.conf import settings
from django.core.mail import send_mail
send_mail('This is the title of the email',
'This is the message you want to send',
settings.DEFAULT_FROM_EMAIL,
[
settings.EMAIL_HOST_USER, # add more emails to this list of you want to
]
)
Make sure your settings are in the project settings.py NOT app settings.py as follows
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
note the empty string for EMAIL_HOST_USER I think this is your mistake
Once you run your virtual python SMTP using
python -m smtpd -n -c DebuggingServer localhost:1025
You will be able to send to your local smtp server with no problem.
Source
Try to enable this option in your google account after you make sure that your mail and password is right.
https://myaccount.google.com/lesssecureapps?pli=1
google blocks the access to insecure apps.
your code seems to be right!
I am trying to send emails from my django app using the the gmail smtp servers. The emails are being sent when I run the application on my local server. But I'm getting an SMTP Authentication Error while using it on heroku.
Traceback - link
settings.py -
# Email configuration.
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '***************#gmail.com'
EMAIL_HOST_PASSWORD = '************'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = '******************#gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
And I have rechecked the account password, also I have enabled the access of less secure apps from my google account. But still I am getting this error.
Disabling CAPTCHA for clients
If you are not using 2-factor authentication and you have verified the credentials in your Python source are correct, follow these steps:
Login to gmail in your browser
Navigate to the DisplayUnclockCaptcha page.
Click the continue button, and you will see the message
Account access enabled Please try signing in to your Google account again from your new device or application.
Run your Python script - your login attempt should be successful.
Try using sendgrid, because gmail smtp has some problem. I too was unable to do using gmail smtp. But it worked perfectly using sendgrid. And this is also free for basic use.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'username'
EMAIL_HOST_PASSWORD = 'userpassword'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'asdf#example.com'
Change from mail(#gmail.com) domain to your company domain .then it will work. we can't use from mail domain #gmail.com, DEFAULT_FROM_EMAIL = '******************#yourcompanydomain.com'
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()
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)