python用 smtp 实现 Email 客户端
时间: 2023-05-30 21:05:42 浏览: 86
Python 中可以使用 smtplib 模块来实现 Email 客户端,具体步骤如下:
1. 导入 smtplib 模块:
```python
import smtplib
```
2. 创建 SMTP 对象:
```python
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
```
其中,host 为 SMTP 服务器主机名,port 为 SMTP 服务器端口号,local_hostname 为本地主机名(可选)。
3. 连接 SMTP 服务器:
```python
smtpObj.connect(host, port)
```
4. 登录 SMTP 服务器:
```python
smtpObj.login(user, password)
```
其中,user 为登录 SMTP 服务器的用户名,password 为登录 SMTP 服务器的密码。
5. 发送邮件:
```python
smtpObj.sendmail(sender, receivers, message)
```
其中,sender 为发件人邮箱地址,receivers 为收件人邮箱地址(可以是一个列表),message 为邮件内容。
6. 退出 SMTP 服务器:
```python
smtpObj.quit()
```
完整代码示例:
```python
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# SMTP 服务器地址和端口号
smtp_server = 'smtp.qq.com'
smtp_port = 587
# 发件人邮箱地址和密码
sender = 'your_email@qq.com'
password = 'your_password'
# 收件人邮箱地址
receivers = ['receiver1@qq.com', 'receiver2@qq.com']
# 邮件内容
message = MIMEText('邮件内容', 'plain', 'utf-8')
message['From'] = Header('发件人名称', 'utf-8')
message['To'] = Header('收件人名称', 'utf-8')
message['Subject'] = Header('邮件主题', 'utf-8')
# 创建 SMTP 对象并连接 SMTP 服务器
smtpObj = smtplib.SMTP(smtp_server, smtp_port)
smtpObj.starttls() # 开启安全连接
smtpObj.login(sender, password) # 登录 SMTP 服务器
# 发送邮件
smtpObj.sendmail(sender, receivers, message.as_string())
# 退出 SMTP 服务器
smtpObj.quit()
```