没有属性:使用 smtplib 发送电子邮件时发现 'audit'

No Attribute : 'audit' found while using smtplib to send emails

我试图通过 发送电子邮件 smtplib,但我总是收到 属性错误 。错误是:

Traceback (most recent call last):
  File "C:\Users\intel\Desktop\Python\test.py", line 24, in <module>
    server = smtplib.SMTP('smtp.gmail.com', 587)
  File "C:\Users\intel\Desktop\Python\smtplib.py", line 195, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Users\intel\Desktop\Python\smtplib.py", line 275, in connect
    sys.audit("smtplib.connect", self, host, port)
AttributeError: module 'sys' has no attribute 'audit'

I know i am getting error because of this line in my code:

# Step 7 - Create the server connection               
server = smtplib.SMTP('smtp.gmail.com', 587)

这是我的代码:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

# Step 2 - Create message object instance
msg = MIMEMultipart()

# Step 3 - Create message body
message = "Test from Python via AuthSMTP"

# Step 4 - Declare SMTP credentials
password = "password"
username = "andrew.whiteman77@gmail.com"

# Step 5 - Declare message elements
msg['From'] = "your.name@your-domain-name.com"
msg['To'] = "your.name@your-domain-name.com"
msg['Subject'] = "Test from Python via AuthSMTP"

# Step 6 - Add the message body to the object instance
msg.attach(MIMEText(message, 'plain'))

# Step 7 - Create the server connection                      # here is the line
server = smtplib.SMTP('smtp.gmail.com', 587)                 # where i am getting error!!!

# Step 8 - Switch the connection over to TLS encryption 
server.starttls()

# Step 9 - Authenticate with the server
server.login(username, password)

# Step 10 - Send the message
server.sendmail(msg['From'], msg['To'], msg.as_string())

# Step 11 - Disconnect
server.quit()

# Step 12 -
print("Successfully sent email message to %s:") % (msg['To'])

当我调试我的文件时,它显示:

任何帮助将不胜感激...

sys.audit() 添加在 Python 3.8.0 之后,调用这个方法你应该使用Python +3.8 Docs Audit Events

This table contains all events raised by sys.audit() or PySys_Audit() calls throughout the CPython runtime and the standard library. These calls were added in 3.8.0 or later.

smtplib Blob CPython 3.7 Github 中你可以看到他们没有使用 sys.audit()。所以,你的问题是关于你的 Python 版本。

您需要将 python 升级到 3.8 才能解决此问题。

python3 -V
sudo apt-get install python3.8
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 2
sudo update-alternatives --config python3

Select 2 或指向 v3.8 的序列号,然后按 Enter

您可以通过

确认您的版本
python3 -V