2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonのimaplibでGmailを取得する際のメールボックス選択

Posted at

pythonの標準ライブラリであるimaplibを用いてGmailを利用する方法は色々紹介されています。
今回はGmailを取得する際のメールボックス選択でつまづいたので、まとめます。

メールボックスの選択

認証後に、メールの取得をする際には、まずメールボックスを選択する必要があります。
特に設定しないとINBOXが指定された状態になってます。
INBOX以外の送信済ボックスや下書きボックスなどの他のメールボックスに移動するには、以下のメソッドでメールボックス名を指定する必要があります。

IMAP4.select()

ここでメールボックス名を調べるには、以下のメソッドでできます。

IMAP4.list()

私の環境では、IMAP4.list()の結果は以下のようになっていました。


from imaplib import IMAP4_SSL
from pprint import pprint
user = 'xxx'
passwd = 'xxx'
gmail = IMAP4_SSL("imap.gmail.com", '993')
gmail.login(user, passwd)
mboxes = gmail.list()

pprint(mboxes[1])
[b'(\\HasNoChildren) "/" "INBOX"',
 b'(\\HasChildren \\Noselect) "/" "[Gmail]"',
 b'(\\All \\HasNoChildren) "/" "[Gmail]/&MFkweTBmMG4w4TD8MOs-"',
 b'(\\HasNoChildren \\Trash) "/" "[Gmail]/&MLQw33ux-"',
 b'(\\Flagged \\HasNoChildren) "/" "[Gmail]/&MLkwvzD8TtgwTQ-"',
 b'(\\Drafts \\HasNoChildren) "/" "[Gmail]/&Tgtm+DBN-"',
 b'(\\HasNoChildren \\Junk) "/" "[Gmail]/&j,dg0TDhMPww6w-"',
 b'(\\HasNoChildren \\Sent) "/" "[Gmail]/&kAFP4W4IMH8w4TD8MOs-"',
 b'(\\HasNoChildren \\Important) "/" "[Gmail]/&kc2JgQ-"']

ここで、先程のIMAP4.select()を使って、例えば送信済ボックスに移動する場合は、以下のように各リストの末尾にある[Gmail]xxxxの部分で指定することができます。


gmail.select('[Gmail]/&kAFP4W4IMH8w4TD8MOs-')
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?