Problem importing MBOX files into Gmail and applying system labels

40 views Asked by At

I'm trying to import MBOX files into Gmail via Python script. The MBOX files are located within the "import" folder, and the MBOX file name should be the label name within Gmail.

For custom labels, this works. If the label is present, it will be assigned and if not it will be created. When I try to import the "Trash.mbox" file, I get an error:

Failed to retrieve or create label 'Trash': <HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Invalid label name". Details: "[{'message': 'Invalid label name', 'domain': 'global', 'reason': 'invalidArgument'}]">

As this just occurs with system labels, I assume I'm missing some limitations. I checked the "Manage labels" article from Google and beside "SENT" and "DRAFT", I should be able to apply the other labels.

def create_label(service, label_name, parent_label_id=None):
    label = {'name': label_name}
    if parent_label_id:
        label['parent'] = parent_label_id
    
    try:
        created_label = service.users().labels().create(userId='me', body=label).execute()
        return created_label['id']
    except Exception as e:
        labels = service.users().labels().list(userId='me').execute().get('labels', [])
        for existing_label in labels:
            if existing_label['name'] == label_name:
                return existing_label['id']
        raise e

def import_mbox_to_gmail(service, mbox_path):
    for root, dirs, files in os.walk(mbox_path):
        for file in files:
            if file.endswith('.mbox'):
                full_filename = os.path.join(root, file)
                labelname, _ = os.path.splitext(file)

                mbox = mailbox.mbox(full_filename)

                try:
                    label_id = create_label(service, labelname)
                except Exception as e:
                    labels = service.users().labels().list(userId='me').execute().get('labels', [])
                    for existing_label in labels:
                        if existing_label['name'] == labelname:
                            label_id = existing_label['id']
                            break
                    else:
                        print(f"Failed to retrieve or create label '{labelname}': {e}")
                        continue

                imported_count = 0
                for index, message in enumerate(mbox):
                    try:
                        message_content = message.as_string()
                        encoded_content = message_content.encode('utf-8')
                        message_data = io.BytesIO(encoded_content)

                        metadata_object = {'labelIds': [label_id]}
                        media = MediaIoBaseUpload(message_data, mimetype='message/rfc822')

                        message_response = service.users().messages().import_(
                            userId='me',
                            fields='id',
                            body=metadata_object,
                            media_body=media).execute()

                        imported_count += 1
                        print(f"{imported_count}/{len(mbox)} | {full_filename} | {labelname}")
                    except Exception as e:
                        print(f"Failed to import message {index + 1} in {file}: {e}")
                mbox.close()
0

There are 0 answers