Search code examples
pythonconnectionoffice365

How do I resolve a connection error when sending an email through outlook with python?


I am trying to send an email with python, because I have to send many emails in bulk and would like to do so with python. The code that I have written is below. When I run this however, I get the following error

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

I think this might be a problem with the setup in Outlook, but I am unsure.

import smtplib

with smtplib.SMTP('smtp.outlook365.com',587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    
    smtp.login('email@address.com','password')
    
    subject = 'This is a test.'
    body = 'wonder if this works!'
    
    msg = f'Subject: {subject}\n\n{body}'
    
    smtp.sendmail('sender@email.com','receiver@email.com',msg)

Solution

  • Check the address of the smtp server, referring to the Microsoft documentation I saw that the address is different.

    SMTP server name smtp.office365.com

    https://support.microsoft.com/en-us/office/pop-imap-and-smtp-settings-for-outlook-com-d088b986-291d-42b8-9564-9c414e2aa040