Office365 smtp server does not respond to ehlo() in python
Asked Answered
O

3

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?

Olatha answered 26/6, 2017 at 16:1 Comment(0)
G
4

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')
Godart answered 23/11, 2022 at 12:9 Comment(0)
A
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()
Alexina answered 1/10, 2020 at 18:44 Comment(0)
N
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.

Neigh answered 20/3, 2023 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.