PythonでGmailに送信されたメールの内容と添付ファイルを取得する
Pythonでメールの受信方法がよくわからず苦戦したのでメモしておきます。gmailでの設定
IMAP4での接続を許可します。
おそらく、デフォルトで許可になっていると思いますが、確認方法は画面右上の設定ボタンから[設定]を選択。

[メール転送とPOP/IMAP]タブを選択し、IMAPアクセスのステータスが[IMAP有効]になっていればOKです。

また、事前にこんな画像の添付付きのメールを送っておきました。

サンプルプログラム
メールサーバーは「imap.gmail.com」
ユーザー名は使用しているgmailのアドレス。
パスワードはそのメールアドレスを閲覧するときのものを指定します。
また、添付ファイルは一旦cStringIOのオブジェクトに突っ込んでおくことにしました。
解析時に必要であればファイルに出力して確認します。
- # -*- coding:utf-8 -*-
- import imaplib,email,email.Header
- import time
- import cStringIO
- class imap4mail(object):
- def __init__(self, data):
- """
- コンストラクタで与えられたメールデータの解析を実行する
- """
- self.files = {}
- #メッセージをパース
- msg = email.message_from_string(data)
- #タイトル取得
- self.title = self.decode(msg.get('Subject'))
- #送信者取得
- self.sender = self.decode(msg.get('From'))
- #送信日付取得
- self.date = self.get_format_date(msg.get('Date'))
- #添付ファイルを抽出
- for part in msg.walk():
- if part.get_content_maintype() == 'multipart':
- continue
- #ファイル名を取得
- filename = part.get_filename()
- #ファイル名が取得できなければ本文
- if not filename:
- self.body = self.decode_body(part)
- #ファイル名が存在すれば添付ファイル
- else:
- tmpfile = cStringIO.StringIO()
- tmpfile.write(part.get_payload(decode=1))
- self.files[filename] = tmpfile
- def decode(self, dec_target):
- """
- メールタイトル、送信者のデコード
- """
- decodefrag = email.Header.decode_header(dec_target)
- title = ''
- for frag, enc in decodefrag:
- if enc:
- title += unicode(frag, enc)
- else:
- title += unicode(frag)
- return title
- def decode_body(self, part):
- """
- メール本文のデコード
- """
- body = ''
- charset = str(part.get_content_charset())
- if charset:
- body = unicode(part.get_payload(), charset)
- else:
- body = part.get_payload()
- return body
- def get_format_date(self, date_string):
- """
- メールの日付をtimeに変換
- http://www.faqs.org/rfcs/rfc2822.html
- "Jan" / "Feb" / "Mar" / "Apr" /"May" / "Jun" / "Jul" / "Aug" /"Sep" / "Oct" / "Nov" / "Dec"
- Wed, 12 Dec 2007 19:18:10 +0900
- """
- format_pattern = '%a, %d %b %Y %H:%M:%S'
- #3 Jan 2012 17:58:09という形式でくるパターンもあるので、
- #先頭が数値だったらパターンを変更
- if date_string[0].isdigit():
- format_pattern = '%d %b %Y %H:%M:%S'
- return time.strptime(date_string[0:-6], format_pattern)
- def analize_mail(mail):
- #取得したメールの内容を表示
- print( mail.sender )
- print( mail.date )
- print( mail.title )
- print( mail.body)
- for key, value in mail.files.items():
- print key
- with open(key, 'w') as f:
- f.write(value.getvalue())
- if __name__ == "__main__":
- host = 'imap.gmail.com'
- user = 'example@gmail.com'
- password = 'password'
- mailbox = 'INBOX'
- #メールサーバ指定
- M = imaplib.IMAP4_SSL(host=host)
- #ログイン
- M.login(user, password)
- #メールボックス選択
- M.select(mailbox)
- typ, data = M.search(None, 'ALL')
- for num in data[0].split():
- typ, data = M.fetch(num, '(RFC822)')
- mail = imap4mail(data[0][1])
- analize_mail(mail)
- M.close()
- M.logout()
実行してみると、非常に素っ気無いですがメールの内容が確かに解析できてます。
スクリプトを実行した階層に「image.jpg」という名前で添付ファイルが
取得できているはずです。
送信者の名前 <sample@mail.example.com>
time.struct_time(tm_year=2012, tm_mon=1, tm_mday=3, tm_hour=17, tm_min=58, tm_sec=9, tm_wday=1, tm_yday=3, tm_isdst=-1)
メールの件名
メールの本文
image.jpg
機種依存文字や、送信元のメーラーによるデータの差異が怖いところですが、
とりあえずメールの受信が行えました。
【参考URL】
0.10. imaplib ― IMAP4 プロトコルクライアント
http://www.python.jp/doc/release/library/imaplib.html
15.3. time ― 時刻データへのアクセスと変換
http://www.python.jp/doc/release/library/time.html
- 関連記事
コメント