Search code examples
djangoemailsmtplib

It's slow to send email by the default EmailBackend of django 1.11 using Microsoft business email account


I'm using the default EmailBackend of Django 1.11, I just simply called the send_mail method as the ref. document said, here are my settings of the SMTP server:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'oalite@xxx.com'
EMAIL_HOST_PASSWORD = 'xxxxx'
EMAIL_SUBJECT_PREFIX = '[OALite Admin]'

Here is my log outputted by smtplib.py:

reply: b'250-CHUNKING\r\n'
reply: b'250 SMTPUTF8\r\n'
reply: retcode (250); Msg: b'SG2PR06CA0180.outlook.office365.com Hello [85.203.47.85]\nSIZE 157286400\nPIPELINING\nDSN\nENHANCEDSTATUSCODES\nAUTH LOGIN XOAUTH2\n8BITMIME\nBINARYMIME\nCHUNKING\nSMTPUTF8'
send: 'AUTH LOGIN b2FBaXRl0GlyaXhpLmNvb0==\r\n'
reply: b'334 UGFzc3dvcmQ6\r\n'
reply: retcode (334); Msg: b'UGFzc3dvcmQ6'
send: 'QEdBbH1w0DJuSwY=\r\n

>>>>>>>>>>>>>>>>>> halted here for about 15s to wait the reply <<<<<<<<<<<<<<<<<<<

reply: b'235 2.7.0 Authentication successful target host BLUPR04MB420.namprd04.prod.outlook.com\r\n'
reply: retcode (235); Msg: b'2.7.0 Authentication successful target host BLUPR04MB420.namprd04.prod.outlook.com'
send: 'mail FROM:<oalite@xxx.com> size=943\r\n'
reply: b'250 2.1.0 Sender OK\r\n'
reply: retcode (250); Msg: b'2.1.0 Sender OK'
send: 'rcpt TO:<user.foo@xxx.com>\r\n'
reply: b'250 2.1.5 Recipient OK\r\n'

Please note that I was using the business email account of Microsoft, the domain xxx.com actually is our company domain name.

I have no idea why it took 15s to authenticate, it's very fast to send emails using the outlook desktop app with the same account. Is it faster to use Exchange protocol then to use SMTP protocol?

Thanks for your help!


Solution

  • A few options for quickly sending outgoing mail from views, when authentication is slow:

    • Use celery to offload mail sending to an offline task.
    • Install a local (forwarding) mail server on your host. On linux this can be accomplished easily with postfix. You can configure the mail server to connect to your business email account.
    • Both :-)

    There seems to be a REST API to connect to outlook.com - so you can also write your own mail backend for sending mail via HTTP.