Question

import smtplib
#SERVER = "localhost"

FROM = 'monty@python.com'

TO = ["jon@mycompany.com"] # 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.

Was it helpful?

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.

OTHER TIPS

Try This for mail with attachments using gmail,replace the appropriate values for other smtp servers.

 def mail(to, subject, text, files=[]):
   msg = MIMEMultipart()

   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   for file in files:
       part = MIMEBase('application', "octet-stream")
       part.set_payload( open(file,"rb").read() )
       Encoders.encode_base64(part)
       part.add_header('Content-Disposition', 'attachment; filename="%s"'% os.path.basename(file))
       msg.attach(part)

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

Sample Example :

attachements_path=[]
attachements_path.append(<file>)
mail(<to_mail_id>,<subject>,<body>,attachements_path)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top