'How can I call the connection of a SMTP server outside the function in Python?

I wanted to send multiple messages with one connection using SMTPLIB, but I wanted to create a connection and send the messages dynamically.

I was wondering what i've done wrong, beucase many other libs can hold its connection.

import smtplib

def connect():
    cred = {
            'uid': '[email protected]',
            'pwd': 'xxxxxxx'
            }
    
    with smtplib.SMTP('smtp.live.com', 587) as smtp:
        smtp.ehlo()
        smtp.starttls() #TLS used to encrypt the message
        smtp.ehlo()
        smtp.login(cred['uid'], 
                   cred['pwd'])
        
    return smtp

smtp = connect()

smtp.send_message( -Some generic message-)

Error : SMTPServerDisconnected: please run connect() first



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source