module 'socket' has no attribute 'SMTP'
时间: 2023-12-16 22:05:10 浏览: 66
这个错误通常是因为你在导入socket模块时使用了错误的语法。socket模块不包含SMTP属性,因此如果你想使用SMTP功能,应该导入smtplib模块。以下是一个使用smtplib模块发送电子邮件的例子:
```python
import smtplib
# 设置邮件服务器地址和端口号
smtp_server = 'smtp.example.com'
smtp_port = 587
# 设置发件人和收件人
from_addr = 'your_email@example.com'
to_addr = 'recipient@example.com'
# 设置登录信息
username = 'your_email@example.com'
password = 'your_email_password'
# 构造邮件内容
msg = 'Subject: Test email\n\nThis is a test email.'
# 发送邮件
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.sendmail(from_addr, to_addr, msg)
server.quit()
print('Email sent successfully!')
except Exception as e:
print('Something went wrong:', e)
```
阅读全文