Search code examples
pythonpython-3.xsmtpattributeerrorsmtplib

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


I was trying to send emails through smtplib, but i always get an Attribute error. The error is:

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)

Here is my code:

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 = "[email protected]"

# Step 5 - Declare message elements
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"
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'])

When i debug my file, it shows that: Attribute error in module itself

Any help will be appreciated...


Solution

  • sys.audit() added after Python 3.8.0, to call this method you should use 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.

    In smtplib Blob CPython 3.7 Github you can see that they didn't use sys.audit(). So, your problem is about your Python version.