python解析提取.eml邮件内容及附件

import re
import os
import email
from email.header import decode_header
from email.utils import parsedate_to_datetime


def parse_eml(eml_fp, attr_dir):
    """
    eml文件解析
    :params eml_fp: eml文件路径
    :params attr_dir: 附件保存目录
    """
    if not os.path.exists(attr_dir):
        os.makedirs(attr_dir)

    # 读取eml文件
    with open(eml_fp, "r") as file:
        eml_content = file.read()
    # 转为email对象
    msg = email.message_from_string(eml_content)

    # 邮件主题
    subject_bytes, subject_encode = decode_header(msg["Subject"])[0]
    if subject_encode:
        subject = subject_bytes.decode(subject_encode)
    else:
        subject = subject_bytes
    print("主题:", subject)

    # 邮件发件人
    from_ip = re.search("<(.*)>", msg["from"]).group(1)
    print("发件人邮箱:", from_ip)
    from_name = decode_header(msg["from"].split("<")[0].strip())
    if from_name:
        if from_name[0] and from_name[0][1]:
            from_n = from_name[0][0].decode(from_name[0][1])
        else:
            from_n = from_name[0][0]
    print("发件人名称:", from_n)

    # 邮件时间
    received_date = parsedate_to_datetime(msg["date"])
    print("接收时间:", received_date)

    # 邮件正文及附件
    for par in msg.walk():
        if not par.is_multipart():  # 判断是否为multipart,里面的数据不需要
            name = par.get_param("name")  # 获取附件的文件名
            if name:  
                # 附件
                fname = decode_header(name)[0]
                if fname[1]:
                    attr_name = fname[0].decode(fname[1])
                else:
                    attr_name = fname[0]
                print("附件名:", attr_name)
                # 解码附件内容
                attr_data = par.get_payload(decode=True)
                attr_fp = os.path.join(attr_dir, attr_name)
                with open(attr_fp, 'wb') as f_write:
                    f_write.write(attr_data)
            else:  
                # 正文
                text_char = par.get_content_charset()
                if "text/plain" in par["content-type"]:  # 文本正文
                    body = par.get_payload(decode=True).decode(text_char)
                    print("邮件正文:", body)
                else:  # html格式正文
                    html_body = par.get_payload(decode=True).decode(text_char)
                    print("HTML正文:", html_body)
            print("-" * 60)
Python3中,可以使用`imaplib`库来下载.eml文件的附件。`imaplib`是Python标准库中用于实现IMAP(Internet Mail Access Protocol,互联网邮件访问协议)客户端的模块。 首先,需要连接到邮箱的IMAP服务器,并进行身份验证。可以使用`IMAP4_SSL`类来建立一个安全的连接。具体代码如下: ```python import imaplib # 连接到邮箱服务器 mail = imaplib.IMAP4_SSL('mail.example.com') # 登录邮箱账号 mail.login('username', 'password') ``` 接下来,可以使用`select()`方法选择邮箱中的某个文件夹(比如"Inbox")来获取邮件。然后,可以使用`search()`方法来搜索包含.eml文件的附件邮件。找到匹配的邮件后,可以使用`fetch()`方法来获取附件内容,并保存为文件。具体代码如下: ```python # 选择Inbox文件夹 mail.select('Inbox') # 搜索包含附件邮件 result, data = mail.search(None, 'ALL') mail_ids = data[0].split() # 遍历每封邮件 for mail_id in mail_ids: # 获取邮件内容 result, data = mail.fetch(mail_id, '(RFC822)') raw_email = data[0][1] # 保存.eml文件 with open(f'{mail_id}.eml', 'wb') as f: f.write(raw_email) ``` 最后,使用`close()`方法关闭与IMAP服务器的连接。完整代码如下: ```python import imaplib # 连接到邮箱服务器 mail = imaplib.IMAP4_SSL('mail.example.com') # 登录邮箱账号 mail.login('username', 'password') # 选择Inbox文件夹 mail.select('Inbox') # 搜索包含附件邮件 result, data = mail.search(None, 'ALL') mail_ids = data[0].split() # 遍历每封邮件 for mail_id in mail_ids: # 获取邮件内容 result, data = mail.fetch(mail_id, '(RFC822)') raw_email = data[0][1] # 保存.eml文件 with open(f'{mail_id}.eml', 'wb') as f: f.write(raw_email) # 关闭与IMAP服务器的连接 mail.close() mail.logout() ``` 请将上述代码中的 `'mail.example.com'`、`'username'`和`'password'`替换为您实际的邮箱服务器地址、用户名和密码。 使用以上代码,就可以下载.eml文件的附件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值