Search code examples
pythonemailpython-2.7smtpattributeerror

How would I send an email in python? This code is not working


import smtplib
#SERVER = "localhost"

FROM = '[email protected]'

TO = ["[email protected]"] # must be a list

SUBJECT = "Hello!"

TEXT = "This message was sent with Python's smtplib."

# Prepare actual message

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail

server = smtplib.SMTP('myserver')
server.sendmail(FROM, TO, message)
server.quit()

When I try running this in my python shell in terminal, it gives me this error:

Traceback (most recent call last):
    File "email.py", line 1, in <module>
        import smtplib
    File "/usr/lib/python2.7/smtplib.py", line 46, in <module>
        import email.utils
    File "/home/pi/code/email.py", line 24, in <module>
        server = smtplib.SMTP('myserver')
AttributeError: 'module' object has no attribute 'SMTP'

Doesn't smtplib have the function SMTP? Or should I change my code? Thanks, A.J.


Solution

  • You named your file email.py, which hides the built-in email package. This caused a circular import problem when smtplib tried to import email.utils. Name your file something else.