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 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: flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() 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()