欢迎访问宙启技术站
智能推送

使用Python自动下载邮件附件

发布时间:2024-01-12 18:31:16

以下是使用Python自动下载邮件附件的步骤和示例代码。

步骤1:导入所需的库和模块

import imaplib
import email
import os

步骤2:连接到邮件服务器

# 输入邮件服务器的地址和端口号
imap_server = 'imap.example.com'
port = 993

# 输入登录信息
email_address = 'your_email@example.com'
password = 'your_password'

# 连接到服务器
mail = imaplib.IMAP4_SSL(imap_server, port)

# 登录邮箱
mail.login(email_address, password)

# 选择邮箱
mail.select('inbox')

步骤3:搜索邮件并下载附件

# 搜索邮件,搜索条件可以根据需要自定义
status, data = mail.search(None, 'ALL')

# 获取邮件ID列表
mail_ids = data[0].split()

# 遍历邮件ID列表
for mail_id in mail_ids:
    # 获取邮件数据
    status, data = mail.fetch(mail_id, '(RFC822)')
    msg = email.message_from_bytes(data[0][1])

    # 遍历邮件中的附件
    for part in msg.walk():
        # 判断是否为附件
        if part.get_content_disposition() is not None:
            # 获取附件文件名
            filename = part.get_filename()

            # 保存附件到本地
            if filename:
                filepath = os.path.join('attachments', filename)
                with open(filepath, 'wb') as f:
                    f.write(part.get_payload(decode=True))

步骤4:关闭连接

# 关闭连接
mail.close()
mail.logout()

完整代码示例:

import imaplib
import email
import os

# 连接到邮件服务器
imap_server = 'imap.example.com'
port = 993
email_address = 'your_email@example.com'
password = 'your_password'
mail = imaplib.IMAP4_SSL(imap_server, port)
mail.login(email_address, password)

# 选择邮箱
mail.select('inbox')

# 搜索邮件并下载附件
status, data = mail.search(None, 'ALL')
mail_ids = data[0].split()

for mail_id in mail_ids:
    status, data = mail.fetch(mail_id, '(RFC822)')
    msg = email.message_from_bytes(data[0][1])

    for part in msg.walk():
        if part.get_content_disposition() is not None:
            filename = part.get_filename()
            if filename:
                filepath = os.path.join('attachments', filename)
                with open(filepath, 'wb') as f:
                    f.write(part.get_payload(decode=True))

# 关闭连接
mail.close()
mail.logout()

注意事项:

1. 在运行代码之前,请确保已安装Python以及所需的库。

2. 邮件服务器地址、端口号、邮箱地址和密码需要根据实际情况进行修改。

3. 文件保存路径可以根据需要进行修改,默认保存在当前目录的attachments文件夹中。

希望以上内容对您有帮助!如有任何疑问,请随时追问。