Django配置Office365发邮件,日志通知管理员失效问题咨询
send_mail) Hey there! Let's break down why your Office 365 SMTP setup works with send_mail() but won't send admin error notifications via logging.error(). The key here is the subtle difference in how Django handles direct email sends vs. automated admin log alerts.
1. Default Sender Address Mismatch
Office 365's SMTP server strictly requires the sender email to match either your verified domain or the account used for SMTP authentication. When you use send_mail(), you're probably explicitly setting the from_email parameter to john@contoso.com—but Django's AdminEmailHandler (which handles log notifications to ADMINS) uses the SERVER_EMAIL setting by default, which often defaults to something like root@localhost. Office 365 rejects this mismatched sender address.
Fix:
Update your settings.py to align the default sender with your Office 365 account:
SERVER_EMAIL = 'john@contoso.com' DEFAULT_FROM_EMAIL = 'john@contoso.com'
2. Office 365 Account Security Restrictions
Even with correct SMTP parameters, Office 365 might block the connection due to two common security settings:
- Authenticated SMTP Disabled: Many Office 365 tenants turn off traditional SMTP access by default.
- MFA Enabled: If your
john@contoso.comaccount has multi-factor authentication turned on, you can't use your regular password for SMTP—you need an app-specific password instead.
Fix:
- Enable Authenticated SMTP:
- Log into the Exchange Admin Center → Navigate to Recipients > Mailboxes
- Select
john@contoso.com→ Go to Mailbox Features > Mail Flow Settings - Toggle Authenticated SMTP to enabled if it's off
- Use an App Password (if MFA is active):
- Log into your Microsoft Account → Go to Security > App passwords
- Generate a new app password, then replace your
EMAIL_HOST_PASSWORDinsettings.pywith this value.
3. Misconfigured Admin Email Handler in Logging Settings
If your logging config explicitly sets a from_email for the AdminEmailHandler that doesn't match john@contoso.com, Office 365 will reject the message. This is an easy detail to overlook!
Fix:
Check your LOGGING config in settings.py. Ensure the mail_admins handler either omits the from_email setting or sets it to your Office 365 address:
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', # Remove any invalid from_email line, or set it correctly: # 'from_email': 'john@contoso.com', }, }, 'loggers': { 'django': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, }, }
4. (Low Priority) Azure Network Restrictions
Since send_mail() works, this is unlikely—but double-check that Azure isn't blocking outbound traffic to smtp.office365.com on port 587. Azure Web Apps allow this port by default, but if you have a Network Security Group (NSG) or custom firewall rules, confirm they don't restrict this connection.
内容的提问来源于stack exchange,提问作者El_Merendero

