blob: 3c2ae1a0e7c0b1ada739a8b1d250aa5da726df52 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
from apiclient.discovery import build
from apiclient import errors
from httplib2 import Http
import oauth2client
from oauth2client import client, tools
import os
import json
import base64
import binascii
from email.mime.text import MIMEText
import sys
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
CLIENT_SECRET_FILE = 'secret.json'
APPLICATION_NAME = 'Swaptions'
def get_gmail_service():
"""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.
Returns:
Credentials, the obtained credential.
"""
credential_dir = '.credentials'
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'guillaume.horel@serenitascapital.com.json')
store = oauth2client.file.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
credentials = tools.run_flow(flow, store, flags)
print('Storing credentials to ' + credential_path)
service = build('gmail', 'v1', http=credentials.authorize(Http()))
return service
class EmailMessage(MIMEText):
_service = get_gmail_service()
def msgdict(self):
if sys.version_info[0]==2:
return {'raw': base64.urlsafe_b64encode(self.as_string())}
else:
return {'raw': base64.urlsafe_b64encode(self.as_bytes()).decode()}
def send(self):
try:
message = (self._service.users().messages().send(userId='me', body=self.msgdict())
.execute())
print('Message Id: %s' % message['id'])
except errors.HttpError as 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.
"""
message = EmailMessage('Hello everyone!')
message['to'] = 'guillaume.horel@gmail.com'
message['subject'] = 'pomme'
message.send()
if __name__ == '__main__':
message = main()
|