Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Sep 5, 2019. It is now read-only.

Commit 2fc0d57

Browse files
committed
Gmail api to create and upload files
1 parent 76605db commit 2fc0d57

File tree

2 files changed

+159
-84
lines changed

2 files changed

+159
-84
lines changed

‎msql-backup/google-drive-api.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import httplib2
2+
import os
3+
4+
from googleapiclient.http import MediaFileUpload
5+
from oauth2client import client
6+
from oauth2client import tools
7+
from oauth2client.file import Storage
8+
9+
try:
10+
import argparse
11+
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
12+
except ImportError:
13+
flags = None
14+
15+
# If modifying these scopes, delete your previously saved credentials
16+
# at ~/.credentials/drive-python-quickstart.json
17+
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
18+
CLIENT_SECRET_FILE = 'client_secret.json'
19+
APPLICATION_NAME = 'Drive API Python Quickstart'
20+
21+
22+
def get_credentials():
23+
"""Gets valid user credentials from storage.
24+
25+
If nothing has been stored, or if the stored credentials are invalid,
26+
the OAuth2 flow is completed to obtain the new credentials.
27+
28+
Returns:
29+
Credentials, the obtained credential.
30+
"""
31+
home_dir = os.path.expanduser('~')
32+
credential_dir = os.path.join(home_dir, '.credentials')
33+
if not os.path.exists(credential_dir):
34+
os.makedirs(credential_dir)
35+
credential_path = os.path.join(credential_dir,
36+
'drive-python-quickstart.json')
37+
38+
store = Storage(credential_path)
39+
credentials = store.get()
40+
if not credentials or credentials.invalid:
41+
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
42+
flow.user_agent = APPLICATION_NAME
43+
credentials = tools.run_flow(flow, store, flags)
44+
print('Storing credentials to ' + credential_path)
45+
return credentials
46+
47+
48+
def upload_file(
49+
drive_service, parent_folder_id, file_name, file_path, mime_type):
50+
"""
51+
:param drive_service: discovery.build('drive', 'v3', http=http)
52+
:param parent_folder_id: ID of folder to upload the file
53+
:param file_name: name of the file
54+
:param file_path: path to the file
55+
:param mime_type: mime type of file (ex: image/jpeg)
56+
:return: File id from Google drive
57+
"""
58+
file_metadata = {'name': file_name, 'parents': [parent_folder_id]}
59+
media = MediaFileUpload(file_path,
60+
mimetype=mime_type)
61+
file = drive_service.files().create(body=file_metadata,
62+
media_body=media,
63+
fields='id').execute()
64+
return file.get('id')
65+
66+
67+
def create_folder(drive_service, parent_folder_id, folder_name):
68+
"""
69+
:param drive_service: discovery.build('drive', 'v3', http=http)
70+
:param parent_folder_id: ID of folder to upload the file
71+
:param folder_name: Name of the folder to be created
72+
:return:
73+
"""
74+
file_metadata = {
75+
'name': folder_name,
76+
'parents': [parent_folder_id],
77+
'mimeType': 'application/vnd.google-apps.folder'
78+
}
79+
folder = drive_service.files().create(body=file_metadata,
80+
fields='id').execute()
81+
return folder.get('id')
82+
83+
84+
if __name__ == '__main__':
85+
credentials = get_credentials()
86+
http = credentials.authorize(httplib2.Http())

‎status-update-checker/test.py

Lines changed: 73 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
1-
import httplib2
21
import os
3-
import base64
4-
import email
2+
import httplib2
53
from apiclient import discovery
64
from oauth2client import client
75
from oauth2client import tools
86
from oauth2client.file import Storage
97
from apiclient import errors
108

11-
email_list = []
9+
try:
10+
import argparse
1211

13-
# try:
14-
# import argparse
15-
#
16-
# flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
17-
# except ImportError:
18-
# flags = None
12+
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
13+
except ImportError:
14+
flags = None
1915

2016
# If modifying these scopes, delete your previously saved credentials
2117
# at ~/.credentials/gmail-python-quickstart.json
@@ -33,7 +29,6 @@ def get_credentials():
3329
Returns:
3430
Credentials, the obtained credential.
3531
"""
36-
# This function generates the required credentials required to make api calls
3732
home_dir = os.path.expanduser('~')
3833
credential_dir = os.path.join(home_dir, '.credentials')
3934
if not os.path.exists(credential_dir):
@@ -54,117 +49,111 @@ def get_credentials():
5449
return credentials
5550

5651

57-
def GetMsg(service, user_id, msg_id):
58-
# This user defined message prints the email id's and their total number emails,of the senders who has sent status updates except user's
59-
try:
60-
message = service.users().messages().get(userId=user_id, id=msg_id,
61-
format='metadata').execute()
62-
63-
payload = message["payload"]["headers"]
64-
65-
a = "X-Original-Sender"
66-
# The below part prints the email id's
67-
for d in payload:
68-
if a in d["name"]:
69-
email_list.append(d["value"])
70-
return (email_list)
71-
# mime_msg = email.message_from_string(msg_str)
72-
73-
return "mime_msg"
74-
except errors.HttpError, error:
75-
print ('An error occurred: %s' % error)
76-
77-
7852
def get_label_id(service, user_id, label_name):
79-
foss_label_id = ""
53+
"""
54+
Return the label id of a Gmail label
55+
:param service: Authorized Gmail API service instance.
56+
:param user_id: User's email address. The special value "me"
57+
:param label_name: The name of the label id required
58+
:return: string(label_id)
59+
"""
60+
label_id = ''
8061
try:
8162
response = service.users().labels().list(userId=user_id).execute()
8263
labels = response['labels']
8364
for label in labels:
8465
if label['name'] == label_name:
85-
# print('Label id: %s - Label name: %s' % (label['id'], label['name']))
86-
foss_label_id = label['id']
87-
except errors.HttpError, error:
88-
print('An error occurred: %s' % error)
66+
label_id = label['id']
67+
except errors.HttpError:
68+
print('An error occurred')
8969

90-
return foss_label_id
70+
return label_id
9171

9272

93-
def ListMessagesWithLabels(service, user_id, label_ids=[]):
94-
"""List all Messages of the user's mailbox with label_ids applied.
73+
def list_messages_matching_query(service, user_id, query=''):
74+
"""List all Messages of the user's mailbox matching the query.
9575
9676
Args:
9777
service: Authorized Gmail API service instance.
9878
user_id: User's email address. The special value "me"
9979
can be used to indicate the authenticated user.
100-
label_ids: Only return Messages with these labelIds applied.
80+
query: String used to filter messages returned.
81+
Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
10182
10283
Returns:
103-
List of Messages that have all required Labels applied. Note that the
84+
List of Messages that match the criteria of the query. Note that the
10485
returned list contains Message IDs, you must use get with the
105-
appropriate id to get the details of a Message.
86+
appropriate ID to get the details of a Message.
10687
"""
10788
try:
10889
response = service.users().messages().list(userId=user_id,
109-
labelIds=label_ids).execute()
90+
q=query).execute()
11091
messages = []
11192
if 'messages' in response:
11293
messages.extend(response['messages'])
11394

11495
while 'nextPageToken' in response:
11596
page_token = response['nextPageToken']
116-
response = service.users().messages().list(userId=user_id,
117-
labelIds=label_ids,
118-
pageToken=page_token).execute()
97+
response = service.users().messages().list(
98+
userId=user_id, q=query, pageToken=page_token).execute()
11999
messages.extend(response['messages'])
120-
121100
return messages
122-
except errors.HttpError, error:
123-
print ('An error occurred: %s' % error)
124-
125101

126-
defListMessagesMatchingQuery(service, user_id, query=''):
127-
"""List all Messages of the user's mailbox matching the query.
102+
excepterrors.HttpError:
103+
print('An error occurred')
128104

129-
Args:
130-
service: Authorized Gmail API service instance.
131-
user_id: User's email address. The special value "me"
132-
can be used to indicate the authenticated user.
133-
query: String used to filter messages returned.
134-
Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
135105

136-
Returns:
137-
List of Messages that match the criteria of the query. Note that the
138-
returned list contains Message IDs, you must use get with the
139-
appropriate ID to get the details of a Message.
106+
def get_sender_email_id(service, user_id, msg_id):
107+
"""
108+
This functions return the email id of the sender
109+
:param service: The google service(here Gmail)
110+
:param user_id: The user id of the user
111+
:param msg_id: The message id that is to be retrived
112+
:return: string(email id)
140113
"""
114+
email_id = ''
115+
141116
try:
142-
response = service.users().messages().list(userId=user_id,
143-
q=query).execute()
144-
messages = []
145-
if 'messages' in response:
146-
messages.extend(response['messages'])
117+
message = service.users().messages().get(userId=user_id, id=msg_id,
118+
format='metadata').execute()
147119

148-
while 'nextPageToken' in response:
149-
page_token = response['nextPageToken']
150-
response = service.users().messages().list(userId=user_id, q=query,
151-
pageToken=page_token).execute()
152-
messages.extend(response['messages'])
120+
header_data = message["payload"]["headers"]
153121

154-
return messages
155-
except errors.HttpError, error:
156-
print ('An error occurred: %s' % error)
122+
sender_text = "X-Original-Sender"
123+
124+
# Get email id from header data
125+
for data in header_data:
126+
if sender_text in data["name"]:
127+
email_id = data["value"]
128+
return email_id
129+
130+
except errors.HttpError:
131+
print('An error occurred')
157132

158133

159-
def main(date):
160-
# This is the function which asks the user for his query
134+
def get_status_update_emails(status_update_date):
135+
"""
136+
137+
:param status_update_date: Date of the status update you want to query
138+
:return:
139+
"""
161140
credentials = get_credentials()
162141
http = credentials.authorize(httplib2.Http())
163142
service = discovery.build('gmail', 'v1', http=http)
164-
query = '[foss-2017] Status Update [' + date + ']'
165-
message = []
166-
messgs = ListMessagesMatchingQuery(service, user_id='me', query=query)
167-
for item in messgs:
168-
message = GetMsg(service, user_id="me", msg_id=item['id'])
169-
return message
143+
status_update_date_string = status_update_date.strftime('%d-%m-%Y')
144+
query = '[foss-2017] Status Update [%s]' % status_update_date_string
170145

146+
emails = []
147+
messages = list_messages_matching_query(service, user_id='me', query=query)
148+
149+
for message in messages:
150+
email = get_sender_email_id(
151+
service, user_id="me", msg_id=message['id'])
152+
emails.append(email)
153+
154+
return emails
155+
156+
157+
if __name__ == '__main__':
158+
credentials = get_credentials()
159+
http = credentials.authorize(httplib2.Http())

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /