Python email script fails unless smtplib is first called in interactive window

StackOverflow https://stackoverflow.com/questions/20613687

  •  02-09-2022
  •  | 
  •  

質問

I have a script that sends an email via a mail server. The script only works when I call import smtplib first in the interactive window. Otherwise, I get the following error:

ImportError: No module named MIMEMultipart

Can someone help me understand the underlying reason behind this behavior?

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os

# Fill in the necessary blanks here
gmail_user = "<your user name>"
gmail_pwd = "<your password>"

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

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

    msg.attach(MIMEText(text))

    msg.attach(MIMEText(text))

    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())
    mailServer.close()

mail("<recipient's email>",
     "Hello from python!",
     "This is an email sent with python")
役に立ちましたか?

解決

Could it be that either your script is named "email.py" or that you have an "email.py" (or "email.pyc" etc) file in your current directory ?

他のヒント

I do not get such a result (Python 2.7.6):

$ python
Python 2.7.5 (default, Sep  2 2013, 20:02:46) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from email.MIMEMultipart import MIMEMultipart
>>> 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top