python poplib 附件
时间: 2023-10-12 13:22:10 浏览: 153
下面是一个使用 poplib 库下载邮件附件的示例代码:
```python
import poplib
import email
import os
# 邮箱配置
pop3_server = 'pop3.example.com'
email_address = 'your_email@example.com'
email_password = 'your_email_password'
# 连接到邮箱服务器
server = poplib.POP3(pop3_server)
server.user(email_address)
server.pass_(email_password)
# 获取邮件数量和列表
message_count = len(server.list()[1])
for i in range(message_count):
# 获取邮件
resp, lines, octets = server.retr(i+1)
msg_content = b'\r\n'.join(lines).decode('utf-8')
msg = email.message_from_string(msg_content)
# 获取附件
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if filename:
# 保存附件
folder_name = '附件'
if not os.path.exists(folder_name):
os.makedirs(folder_name)
filepath = os.path.join(folder_name, filename)
with open(filepath, 'wb') as f:
f.write(part.get_payload(decode=True))
# 退出邮箱
server.quit()
```
这段代码会连接到指定的邮箱服务器,获取邮件列表,遍历每一封邮件,获取其中的附件,并将附件保存到本地文件夹中。你需要将 `pop3_server`,`email_address` 和 `email_password` 替换为你自己的邮箱配置。
阅读全文