email.parser.
Parser()的parsestr()和parse()方法都可以用来从原始邮件文件中提取邮件头信息。这两个方法的区别就parsestr处理的是字符串对象,parse处理的是文件对象。
让我们通过两个例子来了解这两个方法的使用。先来看一封邮件的原始信息的一部分:
cat /tmp/email_test1.txt date: Wed, 16 Nov 2016 16:04:44 +0800 From: 3456789 <[email protected]> To: 1234567 <[email protected]> Cc: 23456780 <[email protected]> Reply-To: 3456789 <[email protected]> Subject: email test! X-Priority: 3 X-Has-Attach: no X-Mailer: Foxmail 7.0.1.91[cn] Mime-Version: 1.0 Message-ID: <[email protected]> Content-Type: multipart/alternative; boundary="----=_001_NextPart245273401224_=----"
例1:通过parsestr提取邮件头
#!/usr/bin/python import os from email.parser import Parser def read_mail(path): if os.path.exists(path): with open(path) as fp: email=fp.read() return email else: print "file not exist!" 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‘]
例2:通过parse提取邮件关
#!/usr/bin/python from email.parser import Parser headers = 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‘]
两个例子的返回的结果都是一样的:
Cc: 23456780 <[email protected]> To: 1234567 <[email protected]> From: 3456789 <[email protected]> Subject: email test!
这样我们就完成了邮件头部信息的提取!
时间: 2024-11-05 23:38:03