简体   繁体   中英

smtp errors when trying to send email from python vis office365

def send_mail(to, subject, body_text):
    SERVER = "smtp.office365.com"
    FROM = "myemail@mycompany.com"

    # Prepare actual message
    msg = EmailMessage()
    msg.set_content(body_text, subtype='html')
    msg['Subject'] = subject
    msg['From'] = FROM
    msg['To'] = to

    # Send the mail
    server = smtplib.SMTP(SERVER, 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login("myemail@mycompany.com", "password")
    server.send_message(msg)
    server.quit()

I have this function for sending emails. This is giving me error -

smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server.

I tried to follow some of the answers here - STARTTLS extension not supported by server and modified my code to remove server.ehlo() before server.starttls() but that gives this error -

smtplib.SMTPHeloError: (501, b'5.5.4 Invalid domain name [SN2PR01CA0061.prod.exchangelabs.com]')

Also tried running by removing the line server.starttls() which gives this error -

smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.

The send_email function was working fine up until now when I changed my modem from Xfinity standard rented modem to store bought Netgear Nighthawk C7000. My internet service provider is Xfinity. I don't know if this is an issue but felt like I should mention since this is the only thing that has changed since email sending stopped working.

Figured out the issue -

Debugging the issue - Add server.set_debuglevel(1) after server = smtplib.SMTP(SERVER, 587) to get the response:

send: 'ehlo DESKTOP-B47NVUE.hsd1.tx.comcast.net.\r\n'
reply: b'501 5.5.4 Invalid domain name [SN4PR0701CA0045.namprd07.prod.outlook.com]\r\n'
reply: retcode (501); Msg: b'5.5.4 Invalid domain name [SN4PR0701CA0045.namprd07.prod.outlook.com]'

In addition to the above response, it also raises this:

File "C:\Users\Dhruv Gami\AppData\Local\Programs\Python\Python36\lib\smtplib.py", line 752, in starttls
    "STARTTLS extension not supported by server.")
smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server.

Solving - I used the answer given here - Office365 smtp server does not respond to ehlo() in python to solve it.

Basically use server.ehlo('mylowercasehost') in the send_mail code at both places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM