除非在交互式wind中首先调用smtplib,否则Python电子邮件脚本将失败

2024-03-28 22:54:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个通过邮件服务器发送电子邮件的脚本。只有当我在交互窗口中首先调用import smtplib时,该脚本才起作用。否则,我得到以下错误:

ImportError: No module named 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")

Tags: totextfromimport脚本youremailmsg
2条回答

是不是你的剧本被命名为“电子邮件.py“或者你有一个”电子邮件.py“(或”电子邮件.pyc“etc)文件在当前目录中?在

我没有得到这样的结果(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
>>> 

相关问题 更多 >