网络编程
位置:首页>> 网络编程>> Python编程>> 详解python实现邮件解析的方法

详解python实现邮件解析的方法

作者:Yunlord  发布时间:2023-02-19 04:03:20 

标签:python,邮件,解析

前言

如何通过python实现邮件解析?邮件的格式十分复杂,主要是mime协议,本文主要是从实现出发,具体原理可以自行研究。

一、安装

通过mailgun开源的Flanker库实现邮件解析。该库包含了邮件地址解析和邮件mime格式解析。

输入以下命令:


pip install flanker

二、代码实现

1.邮件头


def emlAnayalyse(path):
   with open(path, 'rb') as fhdl:
       raw_email = fhdl.read()
       eml = mime.from_string(raw_email)
       subject = eml.subject
       eml_header_from = eml.headers.get('From')
       eml_header_to = eml.headers.get('To')
       eml_header_cc=eml.headers.get('Cc')
       eml_time = eml.headers.get('Date')
       # get_annex(eml, '1')
       eml_attachs=attachEml1(eml)
       eml_body = contentEml(eml)
       f = HTMLFilter()
       f.feed(eml_body)
       print(f.text)
def main():
   path='邮件名.eml'
   emlAnayalyse(path)
if __name__ == "__main__":
   main()

其中eml.header包含发送人,收件人,抄送人,时间等头信息。

2.邮件正文


# 邮件正文
def contentEml(eml):
   # 判断是否为单部分
   if eml.content_type.is_singlepart():
       eml_body = eml.body
   else:
       eml_body = ''
       for part in eml.parts:
           # 判断是否是多部分
           if part.content_type.is_multipart():
               eml_body = contentEml(part)
           else:
               if part.content_type.main == 'text':
                   eml_body = part.body
   return eml_body

通过回调函数,取出邮件正文部分

3.邮件附件


def attachEml1(eml):
   for part in eml.parts:
       if not part.content_type.is_multipart():    
           name = part.detected_file_name
           with open(name, 'wb') as annex:
               annex.write(part.body)

通过content_type.is_multipart()判断是否为附件,将其保存下来。

来源:https://blog.csdn.net/kobepaul123/article/details/121962260

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com