Python Common Module Email----Extract header information from the original message

Source: Internet
Author: User



cat/tmp/email_test1.txtdate:wed, 16:04:44 +0800from:3456789 <[email protected]>to:1234567 <[email protected]>cc:23456780 <[email protected]>reply-to:3456789 <[email protected]>subject:email test! X-priority:3x-has-attach:nox-mailer:foxmail[cn]mime-version:1.0message-id: <[email protected]> content-type:multipart/alternative;boundary= "----=_001_nextpart245273401224_=----"

Example 1: Extracting headers from PARSESTR

#!/usr/bin/pythonimport osfrom email.parser import parserdef read_mail (PATH):                          if os.path.exists (PATH):                     with open (path) &NBSP;AS&NBSP;FP:     ()              return email             else:                                         print  "file not exist!"       &Nbsp;         raw_email=read_mail ('/tmp/email_test1.txt ')     #将邮件读到一个字符串里面headers  =parser () parsestr (raw_email) #经过parsestr处理过后生成一个字典print   ' cc: %s '  % headers[' Cc ']print  ' to: %s '  % headers[' to ']print  ' From: %s '  %  headers[' from ']print  ' subject: %s '  % headers[' Subject ']

Example 2: Extracting a message by using parse

#!/usr/bin/pythonfrom email.parser Import parserheaders = Parser (). Parse (open ('/tmp/email_test1.txt ', ' R ')) print ' Cc: %s '% headers[' Cc ']print ' to:%s '% headers[' to ']print ' from:%s '% headers[' from ']print ' Subject:%s '% headers[' Subject ' ]

The results of the return of the two examples are the same:

cc:23456780 <[email protected]>to:1234567 <[email protected]>from:3456789 <[email protected]> Subject:email test!

So we have finished the message header information extraction!

This article is from the "Always on the Road" blog, please be sure to keep this source

Python Common Module Email----Extract header information from the original message

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.