How to send email via Django?

Viewed 215426

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?

13 Answers

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