使用Python脚本发送电子邮件

2024-06-10 17:25:43 发布

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

我试图写一个功能,将自动发送电子邮件到一个特定的帐户。当我运行代码时,会收到错误消息:

Email could not send
Traceback (most recent call last):
  File "email.py", line 1, in <module>
    import smtplib
  File "C:\Users\User\Anaconda3\lib\smtplib.py", line 47, in <module>
    import email.utils
ModuleNotFoundError: No module named 'email.utils'; 'email' is not a package

这是我写的代码:

import smtplib
import logindetails
def send_email(subject, msg):
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(logindetails.EMAIL_ADDRESS, logindetails.PASSWORD)
        message = 'Subject: {}\n\n{}'.format(subject, msg)
        server.sendmail(logindetails.EMAIL_ADDRESS, logindetails.EMAIL_ADDRESS, message)
        server.quit()
        print('Email sent successfully')
    except:
        print('Email could not send')

subject = 'Testing'
msg = 'Hello there how are you today'
send_email(subject, msg)

Tags: 代码importsendserveraddressemailnotmsg
1条回答
网友
1楼 · 发布于 2024-06-10 17:25:43

在模块搜索路径(包括当前工作目录)中,您自己的模块很可能实际被称为email。这将导致Python取而代之地选择该模块,并且它将从标准库中隐藏email模块,从而导致该导入错误

将该模块重命名为其他模块,您应该表现良好

相关问题 更多 >