162

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:

  1. Can't you use localhost(simple ubuntu pc) to send e-mails?

  2. I thought in django 1.3 send_mail() is somewhat deprecated and EmailMessage.send() is used instead?

Paolo Forgia
  • 5,804
  • 7
  • 39
  • 55
Derek
  • 10,866
  • 24
  • 87
  • 149

12 Answers12

173

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

Jordan
  • 29,324
  • 6
  • 51
  • 63
  • 8
    is there an alternative to leaving your password as a plaintext? – ritratt Feb 04 '13 at 16:46
  • 1
    You could use an email service like Mandrill that will let you use a passphrase instead, although I'm not sure that's any more helpful for you. You could also use an encryption key that's installed on your server, and make the line something like EMAIL_HOST_PASSWORD = my_decrypt('abi304hubaushl9rchy2y9fd29') – Jordan Feb 04 '13 at 22:02
  • 28
    put it in an environment variable. Then, EMAIL_HOST_PASSWORD = os.environ['MY_PASSWORD_THAT_YOU_CANT_KNOW'] – Drew Shafer Feb 12 '13 at 23:31
  • 1
    I used the your code verbatim. My gmail account has been blocked after a few days. My server probably sent less than 20 emails per day. Had anyone had a similar issue with google? – eugene Aug 06 '13 at 05:18
  • On a new account, maybe. You could also try using a service like Mandrill. It's basically the same, if you follow their SMTP instructions. – Jordan Aug 06 '13 at 17:02
  • 1
    Thank you ! This saved me a lot of time @Jordan – tgdn Sep 15 '15 at 10:18
  • 8
    SMTPAuthenticationError and I get an email "**Sign-in attempt prevented ... from an app that doesn't meet modern security standards**". Looks like [this](http://i.stack.imgur.com/HdOwJ.png). Workaround by "[turning on access for less secure apps](https://support.google.com/accounts/answer/6010255)". And that [worked](http://i.imgur.com/YoaUCSG.png). – Bob Stein Jan 05 '16 at 19:53
  • Limited FROM address (3rd parameter to `send_mail()`. It can only be an email associated with your gmail account. – Bob Stein Jan 05 '16 at 20:06
  • Is there any alternative to Sendgrid. Please suggest as I'm using subdomain of pythonanywhere.com. – aquaman Oct 19 '16 at 18:06
  • Is there a statement from Google saying that SMTP is disabled for personal/free accounts? This answer says Gmail is no longer allowing SMTP in 2016, but I can confirm the SMTP works just fine with Google Apps for Business if you enable it in the Gmail App settings and use an app token for the password of the user you want to send from. – Jmills Nov 17 '16 at 22:22
57

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.

Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283
  • 3
    Awesome, I just myself an email! The above article mentioned by miku was perfect. Note the small typo correction in the comments of the article. (And I just used my regular computer/localhost. I had not set anything else up before hand.) – user984003 Oct 24 '12 at 16:11
  • 1
    Which article? Could you link it again? – CGFoX Jul 28 '20 at 19:28
44
  1. Create a project: django-admin.py startproject gmail
  2. 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
    
  3. Run interactive mode: python manage.py shell

  4. Import the EmailMessage module:

    from django.core.mail import EmailMessage
    
  5. 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.

Alex Jolig
  • 10,688
  • 19
  • 103
  • 148
15

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?
Muhammad Usman
  • 1,111
  • 2
  • 11
  • 36
ibaggu
  • 341
  • 3
  • 5
14

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

Cognoscis
  • 194
  • 2
  • 11
  • This one didn't work for me for some reason. I kept getting back an error with the password being wrong. Which is strange because i got the credentials direct from Mailgun. – Alex Stewart Jul 05 '15 at 00:11
10

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.

Vini.g.fer
  • 10,633
  • 14
  • 51
  • 78
5

I found using SendGrid to be the easiest way to set up sending email with Django. Here's how it works:

  1. Create a SendGrid account (and verify your email)
  2. 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.

yndolok
  • 4,689
  • 2
  • 35
  • 37
  • 1
    Excellent, but haven't able to get it to work using 'apikey' as username as per documentation, and SendGrid list three dozens permission configurations per apikey for a simple sendmail... – SYK Jan 04 '17 at 07:11
4

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
Srikar Appalaraju
  • 66,073
  • 51
  • 206
  • 260
2

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.

2

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)
Allan Guwatudde
  • 396
  • 3
  • 5
1

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)
Deepak Sharma
  • 860
  • 11
  • 18
  • Documentation and set up have changed since then but the link to the documentation still works and takes you to the correct config. – Julian Oct 23 '20 at 18:01
0

You can use the Gmail service for the mail.

Steps to use Gmail as an email service (Free) in Django:

1: Create a dummy Google account for your contact. 2: Add the following code in settings.py at the bottom.

 EMAIL_HOST = "smtp.gmail.com"
    EMAIL_PORT = 587
    EMAIL_USE_TLS = True
    EMAIL_HOST_USER = "yourdummy@gmail.com"
    EMAIL_HOST_PASSWORD = "dummypassword"
    
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

3: Now in views.py add:

  from django.core.mail import EmailMessage
    # now in your function add this code
    
    messageContent = yourcontent
    msg = EmailMessage(heading, messageContent, settings.EMAIL_HOST_USER,[list of senders email])
    msg.send()

4: Enable these things first for the dummy Gmail account:

a: Go to https://myaccount.google.com/lesssecureapps and enable it. NOTE: First check that you enable this with sign in as your dummy account. b: Now go to https://accounts.google.com/DisplayUnlockCaptcha and click continue.

5: You are ready to use Gmail email services for your contact page.

Bonus:

If you want to send a mail with an HTML template in Django then use this code in views.py.

from django.template.loader import get_template
from django.core.mail import EmailMessage

# add this code in function:
ctx = {
    'subject': subjectin,
    'userMsg': messagein,
   }

heading = Your heading

messageContent = get_template('yourTemplate.html').render(ctx) #sending value on HTML page through context
msg = EmailMessage(heading, messageContent, settings.EMAIL_HOST_USER,
                   [list of emails ])
msg.content_subtype = 'html'
msg.send()
abdeali004
  • 151
  • 1
  • 4