34

I am trying to send an email in Python:

import smtplib


fromaddr = '......................'  
toaddrs  = '......................'  
msg = 'Spam email Test'  

username = '.......'  
password = '.......'

server = smtplib.SMTP('smtp.gmail.com', 587)  
server.ehlo()
server.starttls()
server.login(username, password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()

I understand that this is probably not the correct message format.

Anyways, I get an error:

C:\.....>python email.py
Traceback (most recent call last):
  File "email.py", line 1, in <module>
    import smtplib
  File "C:\.....\Python\lib\smtplib.py", line 47,
 in <module>
    import email.utils
  File "C:\.....\email.py", line 15, in
<module>
    server = smtplib.SMTP('smtp.gmail.com', 587)
AttributeError: 'module' object has no attribute 'SMTP'

I don't quite understand what I am doing wrong here... Anything incorrect?

NOTE: All the periods are replacements for password/email/file paths/etc.

Jacob Kudria
  • 2,200
  • 3
  • 17
  • 18

2 Answers2

139

Python already has an email module. Your script's name is email.py, which is preventing smtplib from importing the built-in email module.

Rename your script to something other than email.py and the problem will go away.

Blender
  • 289,723
  • 53
  • 439
  • 496
0
import smtplib
conn = smtplib.SMTP('imap.gmail.com',587)
conn.ehlo()
conn.starttls()
conn.login('youremail@gmail.com', 'your_password')

conn.sendmail('from@gmail.com','to@gmail.com','Subject: What you like? \n\n Reply Reply Reply')
conn.quit()
Muneer Ahmad
  • 195
  • 1
  • 3
  • 3
    Your answer would be way better if you added a brief explanation on what's going on here. – Bonifacio2 Aug 22 '19 at 12:22
  • While what you have written may answer the question, however it does seem a little lacking in [explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) and may illicit confusion to other users. Can you please expand upon your answer so that it is clearer and more accessible? This will make for better answers and help future users understand how the problem was solved. – Andrew Aug 22 '19 at 13:05