メールヘッダから日付を取得する
呼称: メールヘッダパーサー for Date
目的: メールヘッダから Date フィールドの日付を取得する
特徴: 意図したフォーマットでない場合はそのまま表示する
用例: メール日付を取得する
備考: email モジュールの使い方のお勉強
このプログラム自体にあまり意味はないのですが、メールを真剣に構文解析しようとすると、RFC に準拠していないフォーマットがあったりして、かなり大変のようです。いずれ自分でパーサーを書く日が来るかもしれないので、その日のための勉強ログになります。
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re import time from email import utils from email.parser import Parser def main(f, k, p): try: print '##### ' + f + ' #####' fp = open(f, 'r') try: msg = Parser().parse(fp) parse_msg(msg._headers, k, p) except Exception, err: print 'got exception:\n%s' % (err) return finally: fp.close() except: print 'cannot open file: %s' % (f) return def parse_msg(h, k, p): pre = k + ': ' for i in h: if p.match(i[0]): d = utils.parsedate(i[1]) print 'orig: ' + str(i) if d: print pre + time.strftime('%Y%m%d %H%M%S', d) else: print pre + str(i[1]) if __name__ == '__main__': key = 'date' pattern = re.compile(key, re.IGNORECASE) for file in sys.argv[1:]: main(file, key, pattern)
実行結果。
$ python get_header_date.py sample01.eml sample02.eml sample03.eml ##### sample01.eml ##### orig: ('Date', 'Mon, 03 Aug 2009 09:27:05 +0900') Date: 20090803 092705 ##### sample02.eml ##### orig: ('date', '2009/07/29 10:07:02') Date: 2009/07/29 10:07:02 ##### sample03.eml ##### orig: ('DATE', '2009\xe5\xb9\xb47\xe6\x9c\x8829\xe6\x97\xa5 10:07:02') Date: 2009年7月29日 10:07:02