I have the following code that I am using to send a message from a gmail account to another gmail account:
import smtplib
class GmailSmpt:
global server
server = smtplib.SMTP('smtp.gmail.com','587')
def __init__(self,sendfrom,sendto,usrname,pswd):
self.sendfrom = sendfrom
self.sendto = sendto
self.usrname = usrname
self.pswd = pswd
def connect(self):
msg = 'this is a test message'
server.starttls()
server.login(self.usrname,self.pswd)
server.sendmail(self.sendfrom,self.sendto,msg)
print ("your email has been sent")
def quit(self):
server.quit()
first = GmailSmpt('sendfrom','sendto',
'usrname','pswd')
first.connect()
first.quit()
Instead of having a global variable server, I would like to use “return server” in the “connect” function and then pass server on to the “quit” function. How would I put that into the parameter of def quit(self, ?)? What I would normally do in a non object oriented program is “def quit(self,connect), but in this case I want to be able to call def connect() and def quit() separately.
Thanks!
How about make
serveran attribute of each instance ofGmailSmpt:After all,
server.loginusesself.usrname, andself.pswd, soserver‘s domain of relevance is bound to one instance ofGmailSmpt, so it makes sense to makeserveran attribute of that instance also.PS. If you make
serveran attribute ofself, then you’ll also have to changeserver–>self.serverin the other methods.