O365 SMTP Actively refuses subsequent connections

  Kiến thức lập trình

I am attempting to set up a simple webhook application to receive requests and send off an email based on the payload. The libraries in use are smtplib for SMTP, flask for hosting, and ngrok for tunnels to make it publicly available.

The issue is that the SMTP connections are behaving strangely. I try to be conservative about the connections, and only have them open for exactly long enough to send the email before disconnecting – this shouldn’t be an issue as I don’t expect this to receive a lot of traffic, maybe 5 requests in a week.

If I omit server.connect(), then it will run fine once, and subsequent connections will fail with the error please use connect() first. However, when I include the connect() function, it will not work at all, with error
[WinError 10061] No connection could be made because the target machine actively refused it

Below is the truncated code:

webapp = Flask(__name__)
mailServer = "smtp.office365.com"
port = 587
sender = 'sendermail'
receivers = 'recipientmail'
password = securepassword
server = SMTP(mailServer, port)


def strtngrok():
    # do stuff


def connectEmail():
    # declarations for mail in smtplib, and opening TLS session
    print("Connecting to SMTP Server")
    try:
        emContext = create_default_context()
        server.connect()
        server.ehlo()
        server.starttls(context = emContext)
        server.login(sender, password)
    except SMTPException as e:
        print("Unable to establish connection to SMTP Server")
        print(e)
        return 501
    print("SMTP Server connectedn")
    return
    # End declarations for mail


def generateEmail (payload):
    # do stuff
    msg.attach(MIMEText(html, "html"))
    if connectEmail() == 501:
        return 501
    server.sendmail(sender, receivers.split(","), msg.as_string())
    server.close()
    return

@webapp.route('/mywebhook', methods=['POST'])
def return_response():
    # do stuff


if __name__ == "__main__":
    context = SSLContext(PROTOCOL_TLS_SERVER)
    strtngrok()
    webapp.run(host = "0.0.0.0", port=1453)

I’ve thought that maybe I have some of the SMTP commands mixed up, swapping the positions of ehlo() and login() but no luck.
I have thought about setting up a single connection and leaving it open but it won’t receive frequent enough requests to keep the connection alive, so it would time out very quickly.

Should I create 2 separate functions for SMTP connection, one for initial and one for reconnection? Or have I mixed up the order of the SMTP connections?
I don’t believe it to be a security issue on our server side as we have multiple small applications that use similar connection methods to send email, the main difference with this one is it requires a reconnection later down the line.

All help would be appreciated

New contributor

AV Man is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT