Search code examples
djangosmtpoffice365

Django: send email via Office365


What I have:

  • A domain purchased in webs.com (I'll call it contoso.com);
  • An Office 365 account connected to that domain (my email address is something like [email protected]);
  • A Django application hosted in Azure;

What I want:

I would like to configure Django in order to send emails using my [email protected] 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 = '[email protected]'
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 = '[email protected]'
EMAIL_HOST_PASSWORD = 'yyyyyy'

This time it works but, obviously, the email is sent from [email protected] and not from [email protected].

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', '[email protected]')]

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.',
    '[email protected]',
    ['[email protected]'],
    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