jeremyephron / simplegmail

A simple Gmail API client for applications in Python
MIT License
336 stars 73 forks source link

Adding ability to create new labels in account #120

Open psresnik opened 2 weeks ago

psresnik commented 2 weeks ago

The add_label routine will fail if the label doesn't already exist for the account. Can a create_label_in_account functionality be added? E.g. something along the lines of the following? (I've thought about forking the repo and doing this myself, but I don't have a lot of experience doing that so I thought I'd start with a feature request, thanks...)

    # Define the new label's properties
    label_body = {
        "labelListVisibility": "labelShow",  # Set label visibility in the label list
        "messageListVisibility": "show",     # Set label visibility in the message list
        "name": new_label                     # Set the name of the new label
    }

    try:
        # Create the label
        label = service.users().labels().create(userId='me', body=label_body).execute()
        print(f"Label '{label['name']}' created successfully.")
        return label

    except googleapiclient.errors.HttpError as error:
        print(f"An error occurred: {error}")
        return None
psresnik commented 2 weeks ago

Never mind! The following worked:

def create_label(label):
    gmail = Gmail()
    labels = gmail.list_labels()
    if label not in [label.name for label in labels]:
        print(f"Adding new label {label} to account")
        gmail.create_label(label)
    else:
        print(f"Verified that label {label} exists in account")