ErikT
ErikT

Reputation: 606

How can I prevent a name error error in python?

When I run my program core.py (http://pastebin.com/kbzbBUYd) it returns:

File "core.py", line 47, in texto core.mail(numbersendlist, messagetext) NameError: global name 'core' is not defined

Can anyone tell me what is going on and how I can stop this error?

If it helps, the "import carrier" line in core.py refers to carrier.py (http://pastebin.com/zP2RHbnr)

Upvotes: 2

Views: 9936

Answers (2)

Imran
Imran

Reputation: 91049

You're getting NameError Because there's no such name core defined in your code in either local or global scope. Create a Core object first before calling it's methods.

Also the indentation of texto() is probably wrong. You won't be able to use this function from rest of the module. If you want to use it from other parts of current module or from other modules, declare the function at module level or use the @staticmethod decorator to if you want to make it a static method of the class.

This should work.

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import carrier

class Core:    
    def __init__(self, username, password):
        # code could be added here to auto load these from a file
        self.gmail_user = username
        self.gmail_pwd = password

# Send one text to one number
# TODO: send to multiple addresses

    def mail(self, to, text):
       msg = MIMEMultipart()
       msg['From'] = self.gmail_user
       msg['To'] = to
       msg.attach(MIMEText(text))

       mailServer = smtplib.SMTP("smtp.gmail.com", 587)
       mailServer.ehlo()
       mailServer.starttls()
       mailServer.ehlo()
       mailServer.login(self.gmail_user, self.gmail_pwd)
       mailServer.sendmail(self.gmail_user, to, msg.as_string())
       # Should be mailServer.quit(), but that crashes...
       mailServer.close()


def texto(sendtoaddress, messagetext):
    numbersendlist = []
    for number in sendtoaddress:
        numbersendlist.append(carrier.carriercheck(number))

    core = Core('username', 'password')
    for number in numbersendlist:
        core.mail(number, messagetext)

texto(['1112223333'], 'hi. this better work.')

Upvotes: 6

ephemient
ephemient

Reputation: 204886

core is not a name that you've defined, yet. I expect that you intended to write something like

core = Core('username', 'password')

before calling texto?

Upvotes: 1

Related Questions