Reputation: 352
I have a class sendmail and I am trying to call it in other classes.The argument
will determine which email to send. The argument
in the sendmail class will send mail according to parameters given to it from other classes where it is being called.However,when executing it, I get error message saying argument
not defined.
Here is my code:
#!/usr/bin/python
import smtplib
class sendmail(argument):
TO = '[email protected]'
if argument=='PIR':
SUBJECT = 'PIR'
TEXT = 'Motion is detected'
gmail_sender = '[email protected]'
gmail_passwd = 'mypwd'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join([
'TO: %s' % TO,
'From: %s' % gmail_sender ,
'Subject: %s' % SUBJECT ,
'',
TEXT
])
try:
server.sendmail(gmail_sender, [TO], BODY)
print 'email sent'
except:
print 'error'
server.quit()
Upvotes: 0
Views: 119
Reputation: 184
I think what you're looking for is a static function.
import smtplib
class MailUtils:
@staticmethod
def sendmail(argument):
TO = '[email protected]'
if argument=='PIR':
SUBJECT = 'PIR'
TEXT = 'Motion is detected'
gmail_sender = '[email protected]'
gmail_passwd = 'mypwd'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join([
'TO: %s' % TO,
'From: %s' % gmail_sender ,
'Subject: %s' % SUBJECT ,
'',
TEXT
])
try:
server.sendmail(gmail_sender, [TO], BODY)
print 'email sent'
except:
print 'error'
server.quit()
You would use it by doing this:
import MailUtils
MailUtils.sendmail(argument)
Note: As mentioned in the comments below, this approach works best if the class contains multiple related functions, not just a single one.
Upvotes: 1