python 邮件发送
时间: 2023-10-15 07:29:07 浏览: 40
您好!要使用Python发送电子邮件,您可以使用内置的smtplib库。下面是一个简单的示例代码,演示如何使用SMTP服务器发送电子邮件:
```python
import smtplib
from email.mime.text import MIMEText
# 邮件相关的信息
sender = 'your_email@example.com'
receiver = 'recipient_email@example.com'
subject = 'Hello from Python!'
message = 'This is a test email.'
# 创建邮件对象
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
# 邮件服务器的信息
smtp_server = 'smtp.example.com' # 请替换为您的SMTP服务器地址
smtp_port = 587 # 请根据您的SMTP服务器设置进行修改
# 发送邮件
try:
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.starttls()
smtp_obj.login(sender, 'your_password') # 请替换为您的邮箱密码或授权码
smtp_obj.sendmail(sender, receiver, msg.as_string())
smtp_obj.quit()
print('邮件发送成功!')
except Exception as e:
print('邮件发送失败:', str(e))
```
请注意,上述代码中的`your_email@example.com`、`recipient_email@example.com`、`smtp.example.com`和`your_password`需要根据您自己的情况进行替换。此外,您的SMTP服务器可能需要进行额外的配置和身份验证。
希望这能帮到您!如果您有任何其他问题,请随时提问。