6

I am trying to use Office365 smtp server for automatically sending out emails. My code works previously with gmail server, but not the Office365 server in Python using smtplib.

My code:

import smtplib

server_365 = smtplib.SMTP('smtp.office365.com', '587')

server_365.ehlo()

server_365.starttls()

The response for the ehlo() is: (501, '5.5.4 Invalid domain name [DM5PR13CA0034.namprd13.prod.outlook.com]')

In addition, .starttls() raises a SMTPException: STARTTLS extension not supported by server

Any idea why this happens?

Pratibha
  • 1,730
  • 7
  • 27
  • 46

3 Answers3

2

I had to put SMTP EHLO before and after starttls().

import smtplib
server_365 = smtplib.SMTP('smtp.office365.com', '587')
server_365.ehlo('mylowercasehost')
server_365.starttls()
server_365.ehlo('mylowercasehost')
William Miller
  • 9,839
  • 3
  • 25
  • 46
1

The smtplib ehlo function automatically adds the senders host name to the EHLO command, but Office365 requires that the domain be all lowercase, so when youe default host name is uppercase it errors.

You can fix by explicitly setting sender host name in the ehlo command to anything lowercase.

import smtplib

server_365 = smtplib.SMTP('smtp.office365.com', '587')

server_365.ehlo('mylowercasehost')

server_365.starttls()
Cain
  • 264
  • 1
  • 7
1

Office 365 expects an all-lowercase hostname. SMTP.starttls calls SMTP.ehlo_or_helo_if_needed, so calling SMTP.ehlo with an all-lowercase hostname before SMTP.starttls, i.e.

s.ehlo('lowercasehost')
s.starttls()

should result in a valid domain and allow access -- as other answers indicate.

If, however, SMTP.ehlo_or_helo_if_needed triggers SMTP.ehlo or SMTP.helo during SMTP.starttls for any reason, it will revert to the default hostname. In my case, despite using

s.ehlo('lowercasehost')
s.starttls()

SMTP.ehlo was still called by SMTP.ehlo_or_helo_if_needed in SMTP.starttls and called with the default, invalid hostname. Explicitly setting the default hostname with

s.local_hostname = 'lowercasehost'
s.starttls()

resolved the issue.

William Miller
  • 9,839
  • 3
  • 25
  • 46