前言
如何通過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://www.uj5u.com/houduan/385607.html
標籤:python
上一篇:還不會Python資料可視化? 手把手教你用 Matplotlib 實作資料可視化(珍藏版)
下一篇:Python繪制圣誕樹
