diff options
Diffstat (limited to 'python')
| -rw-r--r-- | python/send_email.py | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/python/send_email.py b/python/send_email.py new file mode 100644 index 00000000..c6ca21b1 --- /dev/null +++ b/python/send_email.py @@ -0,0 +1,73 @@ +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 argparse +#flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() + +SCOPES = 'https://www.googleapis.com/auth/gmail.compose' +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): + def __init__(self, _text, _subtype='plain', _charset=None): + MIMEText.__init__(self, _text, _subtype, _charset) + self._service = get_gmail_service() + + def msgdict(self): + 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() + return message + +if __name__ == '__main__': + message = main() |
