我有一个通过邮件服务器发送电子邮件的脚本.该脚本仅在我import smtplib在交互式窗口中首先调用时才有效.否则,我收到以下错误:
ImportError:没有名为MIMEMultipart的模块
有人能帮我理解这种行为背后的根本原因吗?
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")
Run Code Online (Sandbox Code Playgroud)