{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "Relevant Links:\n",
    "\n",
    "1. Visit https://developers.google.com/gmail/api/quickstart/python\n",
    "\n",
    "2. Click \"Enable the GMail API\", follow the steps and finallly click \"DOWNLOAD CLIENT CONFIGURATION\". Save the \"credentials.json\" file to the current working directory\n",
    "\n",
    "3. Visit https://console.cloud.google.com/\n",
    "\n",
    "4. Create a new project\n",
    "\n",
    "5. Click \"Go to APIs Overview\"\n",
    "\n",
    "6. Click the \"Credentials\" tab on the left. Click \"+ CREATE CREDENTIALS\" at the top and choose \"Service Account\". Give the service account a name and click \"Create\"\n",
    "\n",
    "7. Click on the newly created service account, ensure it is enabled, and click \"ADD KEY\" -> \"Create new key\". Pick \"JSON\" and download the json file and store it in the current working directory.\n",
    "\n",
    "8. Run the cells in this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "\n",
    "from random import random\n",
    "from datetime import datetime\n",
    "import sys\n",
    "\n",
    "import os\n",
    "import pickle\n",
    "import google.oauth2.credentials\n",
    "from email.mime.text import MIMEText\n",
    "import base64\n",
    "\n",
    "from googleapiclient.discovery import build\n",
    "from googleapiclient.errors import HttpError\n",
    "from google_auth_oauthlib.flow import InstalledAppFlow\n",
    "from google.auth.transport.requests import Request"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#set this to the name of the JSON file downloaded in step 7 above\n",
    "os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]= \"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If modifying these scopes, delete the file token_gmail.pickle.\n",
    "SCOPES = ['https://www.googleapis.com/auth/gmail.compose']\n",
    "\n",
    "def main():\n",
    "    \"\"\"Shows basic usage of the Gmail API.\n",
    "    Lists the user's Gmail labels.\n",
    "    \"\"\"\n",
    "    creds = None\n",
    "    # The file token_gmail.pickle stores the user's access and refresh tokens, and is\n",
    "    # created automatically when the authorization flow completes for the first\n",
    "    # time.\n",
    "    if os.path.exists('token_gmail.pickle'):\n",
    "        with open('token_gmail.pickle', 'rb') as token:\n",
    "            creds = pickle.load(token)\n",
    "    # If there are no (valid) credentials available, let the user log in.\n",
    "    if not creds or not creds.valid:\n",
    "        if creds and creds.expired and creds.refresh_token:\n",
    "            creds.refresh(Request())\n",
    "        else:\n",
    "            flow = InstalledAppFlow.from_client_secrets_file(\n",
    "                'credentials.json', SCOPES)\n",
    "            creds = flow.run_local_server(port=0)\n",
    "        # Save the credentials for the next run\n",
    "        with open('token_gmail.pickle', 'wb') as token:\n",
    "            pickle.dump(creds, token)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_authenticated_gmail_service():\n",
    "    \"\"\"\n",
    "    This function uses the token_gmail.pickle file to get an authenticated object used to talk to Gmail\n",
    "    \"\"\"\n",
    "\n",
    "    credentials = None\n",
    "    API_SERVICE_NAME = 'gmail'\n",
    "    API_VERSION = 'v1'\n",
    "    \n",
    "    if os.path.exists('token_gmail.pickle'):\n",
    "        with open('token_gmail.pickle', 'rb') as token:\n",
    "            credentials = pickle.load(token)\n",
    "\n",
    "    return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "service = get_authenticated_gmail_service()  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Core Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_message(sender, to, subject, message_text):\n",
    "    \"\"\"\n",
    "    Create a message for an email.\n",
    "\n",
    "    Args:\n",
    "        sender: Email address of the sender.\n",
    "        to: Email address of the receiver.\n",
    "        subject: The subject of the email message.\n",
    "        message_text: The text of the email message.\n",
    "\n",
    "    Returns:\n",
    "        An object containing a base64url encoded email object.\n",
    "    \"\"\"\n",
    "    message = MIMEText(message_text)\n",
    "    message['to'] = to\n",
    "    message['from'] = sender\n",
    "    message['subject'] = subject\n",
    "    return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def send_message(service, user_id, message):\n",
    "    \"\"\"\n",
    "    Send an email message.\n",
    "\n",
    "    Args:\n",
    "        service: Authorized Gmail API service instance.\n",
    "        user_id: User's email address. The special value \"me\"\n",
    "        can be used to indicate the authenticated user.\n",
    "        message: Message to be sent.\n",
    "\n",
    "    Returns:\n",
    "        Sent Message.\n",
    "    \"\"\"\n",
    "    \n",
    "    try:\n",
    "        message = (service.users().messages().send(userId=user_id, body=message)\n",
    "                   .execute())\n",
    "        print('Message Id: %s' % message['id'])\n",
    "        return message\n",
    "    except Exception as e:\n",
    "        print('An error occurred: %s' % e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Run Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#create a message\n",
    "my_message = create_message('your_email_address', 'your_email_address', 'Subject', 'message text')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#send the message\n",
    "send_message(service, 'me', my_message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
