There are various ways to use Gmail using imaplib, which is the standard library of python. This time I stumbled upon selecting a mailbox when getting Gmail, so I will summarize it.
After authentication, you must first select your mailbox to retrieve your email. If you do not set it in particular, INBOX will be in the specified state. To move to a mailbox other than INBOX, such as a sent box or draft box, you need to specify the mailbox name with the following method.
You can find out the mailbox name here with the following method.
In my environment, the result of ʻIMAP4.list ()` was as follows.
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-"']
Here, if you use ʻIMAP4.select ()earlier, for example, to move to the sent box, you can specify it in the
[Gmail] xxxx` part at the end of each list as shown below. I will.
gmail.select('[Gmail]/&kAFP4W4IMH8w4TD8MOs-')
Recommended Posts