python [整洁的Gmail标签]统一我的Gmail标签的可见性和命名(后来转换为macos finder标签)#gmail #label #tag
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python [整洁的Gmail标签]统一我的Gmail标签的可见性和命名(后来转换为macos finder标签)#gmail #label #tag相关的知识,希望对你有一定的参考价值。
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient import errors
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
import re
# If modifying these scopes, delete your previously saved credentials
# at CLIENT_SECRET_FILE and the CLIENT_SECRET_FILE will be regenerated
SCOPES = 'https://mail.google.com/'
CLIENT_SECRET_FILE = '/Users/Dave/.credentials/client_secret.json'
# I HAVE ADDED THE PROJECTOR PROJECT UNDER THE GMAIL API
# https://console.developers.google.com/apis/dashboard
APPLICATION_NAME = 'Projector'
def get_credentials(filename):
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
**Key Arguments:**
- ``filename`` -- differentiate between home and work emails.
**Returns:**
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
filename)
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def UpdateLabel(service, user_id, label_id, updated_label_object):
"""Update an existing Label.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
label_id: ID of the Label to update.
updated_label_object: Updated Label.
Returns:
Updated Label.
"""
try:
updated_label_object['id'] = label_id
updated_label = (service.users().labels()
.update(userId=user_id, id=label_id,
body=updated_label_object).execute())
try:
print('label id: %s - label name: %s' % (updated_label['id'],
updated_label['name'].encode("utf-8")))
except:
pass
return updated_label
except errors.HttpError, error:
print('An error occurred: %s' % error)
def main():
"""Shows basic usage of the Gmail API.
Creates a Gmail API service object and outputs a list of label names
of the user's Gmail account.
"""
for filename in ["home-gmail.json", "work-gmail.json"]:
credentials = get_credentials(filename)
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
results = service.users().labels().list(
userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
name = label['name']
skip = False
for i in ["CATEGORY_", "["]:
if i in name:
skip = True
if skip:
continue
skip = False
for i in ["TRASH", "DRAFT", "SPAM", "STARRED", "UNREAD", "INBOX", "SENT", "IMPORTANT", "CHAT"]:
if i == name:
skip = True
if skip:
continue
r = re.findall('([A-Z])', name)
if len(r) or "-" in name or " " in name or ":" in name or "," in name:
name = name.encode("utf-8")
print("Renaming %(name)s" % locals())
label['name'] = label['name'].lower().replace(
"-", "_").replace(" ", "_").replace(":", "_").replace("__", "_").replace("__", "_").replace(",", "")
UpdateLabel(service, user_id="me", label_id=label[
'id'], updated_label_object=label)
if labels:
for label in labels:
name = label['name']
skip = False
for i in ["@", "CATEGORY_"]:
if i in name:
skip = True
if skip:
continue
skip = False
for i in ["TRASH", "DRAFT", "SPAM", "STARRED", "UNREAD", "INBOX", "SENT", "IMPORTANT", "CHAT"]:
if i == name:
skip = True
if skip:
continue
if "labelListVisibility" not in label or label["labelListVisibility"] != "labelShowIfUnread":
label["labelListVisibility"] = "labelShowIfUnread"
UpdateLabel(service, user_id="me", label_id=label[
'id'], updated_label_object=label)
if __name__ == '__main__':
main()
以上是关于python [整洁的Gmail标签]统一我的Gmail标签的可见性和命名(后来转换为macos finder标签)#gmail #label #tag的主要内容,如果未能解决你的问题,请参考以下文章
如何将新的 Gmail API 消息/线程 ID 转换为 X-GM-MSGID/X-GM-THRID 和
Python:以pdf格式下载标签(gmail)中的所有电子邮件
如何在 iOS 6 GM 中的标签栏应用程序中使旋转正常工作?
Phone 5 标签栏不工作 - iOS7 和 Xcode GM