2
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.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • You can refer : [http://stackoverflow.com/questions/16512256/no-attribute-smtp-error-when-trying-to-send-email-in-python][1] [1]: http://stackoverflow.com/questions/16512256/no-attribute-smtp-error-when-trying-to-send-email-in-python They are the some problems. – Brightshine Jan 10 '14 at 03:26

2 Answers2

9

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

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)
Naveen Subramani
  • 2,134
  • 7
  • 20
  • 27
  • You could use `email.header.Header` for the `Subject` to support non-ascii characters. To be able to email to multiple recipients, pass a list to `sendmail` (`To` header is still a string). Here's [a code example that demonstrates how to send email (with inline image via gmail over ssl)](http://stackoverflow.com/a/20485764/4279). – jfs Mar 05 '14 at 22:43