使用 IMAP 向 Gmail 添加标签,Python
Add label to Gmail using IMAP, Python
我正在尝试为部分 Gmail 邮件添加标签。这真的是马车。它有效,然后无效,然后仅添加到第一封电子邮件...
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myaccountxyz@gmail.com', mypassword)
mail.select("my-folder") # finds emails with this label
result, data = mail.uid('search', None, 'all')
label_to_add = "label-to-add" # previously created in Gmail
for email_uid in data[0].split():
result, data_single = mail.uid('fetch', email_uid, '(RFC822)')
raw_email = data_single[0][1]
email_message = email.message_from_string(raw_email)
sender = email_message['From']
mail.store(email_uid, '+X-GM-LABELS', '('+label_to_add+')')
# also tried without the parenthesis
mail.store(email_uid, '+X-GM-LABELS', label_to_add)
如果你使用 mail.uid('search'...
你需要使用 mail.uid('store', ...
否则你混合了不对应的 UID 和 MSN(消息序列号),所以有时你很幸运并且你的 UID 发生了低到足以访问 MSN。
我正在尝试为部分 Gmail 邮件添加标签。这真的是马车。它有效,然后无效,然后仅添加到第一封电子邮件...
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myaccountxyz@gmail.com', mypassword)
mail.select("my-folder") # finds emails with this label
result, data = mail.uid('search', None, 'all')
label_to_add = "label-to-add" # previously created in Gmail
for email_uid in data[0].split():
result, data_single = mail.uid('fetch', email_uid, '(RFC822)')
raw_email = data_single[0][1]
email_message = email.message_from_string(raw_email)
sender = email_message['From']
mail.store(email_uid, '+X-GM-LABELS', '('+label_to_add+')')
# also tried without the parenthesis
mail.store(email_uid, '+X-GM-LABELS', label_to_add)
如果你使用 mail.uid('search'...
你需要使用 mail.uid('store', ...
否则你混合了不对应的 UID 和 MSN(消息序列号),所以有时你很幸运并且你的 UID 发生了低到足以访问 MSN。