邮件 python
时间: 2024-08-12 19:05:28 浏览: 42
Python 定制HTML格式电子邮件 Python源码
邮件在Python中可以通过内置的`smtplib`和`email`模块来处理。`smtplib`用于发送电子邮件,而`email`库则负责构建邮件消息、解析邮件地址等。以下是一个简单的例子:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 设置发件人、收件人和SMTP服务器信息
sender = 'your_email@example.com'
receiver = 'recipient_email@example.com'
smtp_server = 'smtp.example.com'
password = 'your_password'
# 创建邮件内容
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = 'Python Email Test'
body = '这是一封通过Python发送的邮件'
msg.attach(MIMEText(body, 'plain'))
# 登录SMTP服务器并发送邮件
try:
server = smtplib.SMTP(smtp_server, 587)
server.starttls() # 加密连接
server.login(sender, password)
text = msg.as_string()
server.sendmail(sender, receiver, text)
print("邮件发送成功")
except Exception as e:
print(f"邮件发送失败: {e}")
server.quit() # 关闭连接
```
阅读全文