Jeff Pang Jeff Pang - 25 days ago 13
Python Question

python failed to import smtplib

I have a script as follow

#!/usr/bin/python
import smtplib
import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

now = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())

fromaddr = "xxx@gmail.com"
toaddr = "yyy@live.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Device Start Up Notification"

body = "Your device is started up %s " % now
msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "abc12345")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()


When i execute this file, it shows error

Traceback (most recent call last):
File "./email.py", line 2, in <module>
import smtplib
File "/usr/lib/python2.7/smtplib.py", line 46, in <module>
import email.utils
File "/home/jypang/email.py", line 4, in <module>
from email.MIMEMultipart import MIMEMultipart
ImportError: No module named MIMEMultipart


The library is installed because I have another script which same as the script above (importing same library) and it's working well.

Please assist, thank you!

Answer

You named your module email which conflicts with standard library module email; stmplib module depends on the standard library module email.

You need to rename email with another name. If there's email.pyc, make sure delete it.