ikvk / imap_tools

Work with email by IMAP
Apache License 2.0
719 stars 83 forks source link

X-GM-LABELS: add support to add gmail label #174

Closed MattSidney closed 2 years ago

MattSidney commented 2 years ago

Is it possible to add support to label gmail emails? see https://developers.google.com/gmail/imap/imap-extensions

Labels may be added to a message using the STORE command in conjunction with the X-GM-LABELS attribute. The following is an example transcript demonstrating the addition of a label to a message:

a011 STORE 1 +X-GM-LABELS (foo)
* 1 FETCH (X-GM-LABELS (\Inbox \Sent Important "Muy Importante" foo))
a011 OK STORE (Success)
ikvk commented 2 years ago

No. This is not a part of imap. I will not make any more exceptions to add unique mail server functions.

besides, as you wrote, it's just mailbox.box.uid("STORE", uid, 'X-GM-LABELS', label)

ikvk commented 2 years ago

*With 0.55 ver it will be mailbox.client.uid("STORE", uid, 'X-GM-LABELS', label)

dzg commented 1 year ago

If anyone needs it, here is a function to add a label to a message in Gmail:

def AddLabel(mailbox, uid, label):
    labels_fetched = mailbox.client.uid("FETCH", uid, "X-GM-LABELS")[1][0]
    labels_bytes = re.search(rb"X-GM-LABELS \((.*?)\)", labels_fetched).group(1)
    labels_string = labels_bytes.decode("utf-8")
    labels_string += " " + label
    return mailbox.client.uid("STORE", uid, "X-GM-LABELS", labels_string)

Note that if you just assign label without fetching existing labels, they will get overwritten.

jamiekarvans commented 5 months ago

If anyone needs it, here is a function to add a label to a message in Gmail:

def AddLabel(mailbox, uid, label):
    labels_fetched = mailbox.client.uid("FETCH", uid, "X-GM-LABELS")[1][0]
    labels_bytes = re.search(rb"X-GM-LABELS \((.*?)\)", labels_fetched).group(1)
    labels_string = labels_bytes.decode("utf-8")
    labels_string += " " + label
    return mailbox.client.uid("STORE", uid, "X-GM-LABELS", labels_string)

Note that if you just assign label without fetching existing labels, they will get overwritten.

actually if the message has no labels it will raise an error so better to avoid it by:

if labels_string != "":
    labels_string += " " + label
else:
    labels_string += label