djangosmtpoffice365

Django: send email via Office365


What I have:

What I want:

I would like to configure Django in order to send emails using my john@contoso.com address.

What I'v done:

I tried this Django configuration:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.office365.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'john@contoso.com'
EMAIL_HOST_PASSWORD = 'xxxxxx'

but it didn't work. So, just for a test, I tried the free Google SMTP server:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'john@gmail.com'
EMAIL_HOST_PASSWORD = 'yyyyyy'

This time it works but, obviously, the email is sent from john@gmail.com and not from john@contoso.com.

What's wrong in the previous configuration? Or maybe I need to make some changes in my Office 365 account?


Update

So far I've tried to receive emails by setting Django's ADMINS variable in this way:

ADMINS = [('Admin Name', 'admin@gmail.com')]

And then I send the email using the logging object:

logging.error("Hello admin!!")

As said, this works only when I use smtp.gmail.com. Today I tried to use the send_mail function:

send_mail(
    'Subject here',
    'Here is the message.',
    'john@gmail.com',
    ['mail@gmail.com'],
    fail_silently=False,
)

And it works both using smtp.gmail.com and smtp.office365.com configuration. Unfortunatelly this can't be a valid solution for me since I need to notify the admin in case of an error or an exception. So, why the send_mail function works with smtp.office365.com and the ADMIN setting don't?


Solution

  • To send email using the Office365 smtp server, the "from" user and the "host" user must be the same. So I added this setting in Django in order to send email to the admins:

    SERVER_EMAIL = EMAIL_HOST_USER