Jie Jenn - gmail api playlist

01_How to use Gmail API to send an email in Python

Part 1 - Start Script, import function from extenal script

01

import the create_service function from the google_api.py script and import the following libraries. The google_api.py script can be found at
https://learndataanalysis.org/google-py-file-source-code/

go back and create your own create service function I did go to the bottom to see

from google_apis import create_service 
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
                                

02

Supply the function with the following variables, and the full scope,

https://mail.google.com/

Make sure you put this scope into a list You Always forget!!!

from google_apis import create_service
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

CLIENT_SECRET_FILE = 'credentials.json'
API_NAME = 'gmail'
API_VERSION = 'v1'
SCOPES = ['https://mail.google.com/']

service = create_service(CLIENT_SECRET_FILE,API_NAME,API_VERSION,SCOPES)
                                

run this script and the autorization window should appear as seen in gettingStarted tutorials codeTops and Jiejenn

Part 2 - Create the message, assign values to mimeMessage

01

create the message, and assign the following values to mimeMessage[] which is an instance of the MIMEMultPart review codeTops Part 8 to see how the the email objects work

'plain' is an option for message formate, there are others including html for style

emailMsg = "yo I'm sending emails with python"
mimeMessage = MIMEMultipart()
mimeMessage['to'] = 'tstudystuff@gmail.com'
mimeMessage['subject'] = 'yo yo'
mimeMessage.attach(MIMEText(emailMsg, 'plain'))

raw_string = base64.urlsafe_b64encode(mimeMessage.as_bytes().decode())
                                

The red line doesn't work below is corrected by chatGPT

02

The code he jieJenn provides does NOT work, make sure the line with
raw_string = base64.urlsafe_b64encode(mimeMessage.as_bytes()).decode('utf-8')
looks like this.

Below is the complete code and will work

from google_apis import create_service
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

CLIENT_SECRET_FILE = 'credentials.json'
API_NAME = 'gmail'
API_VERSION = 'v1'
SCOPES = ['https://mail.google.com/']

service = create_service(CLIENT_SECRET_FILE,API_NAME,API_VERSION,SCOPES)

emailMsg = "yo I'm sending emails with python"
mimeMessage = MIMEMultipart()
mimeMessage['to'] = 'tstudystuff@gmail.com'
mimeMessage['subject'] = 'yo yo'
mimeMessage.attach(MIMEText(emailMsg,'plain'))
raw_string = base64.urlsafe_b64encode(mimeMessage.as_bytes()).decode('utf-8')

message = service.users().messages().send(userId='me', body={'raw': raw_string}).execute()
                                

Part 3 - my own google_api.py script and full script

01

my google_api.py script

This is my simplified service script

import os
import datetime
from collections import namedtuple
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request

def create_service(client_secret_file, api_name, api_version, *scopes, prefix=''):
    CLIENT_SECRET_FILE = client_secret_file
    API_SERVICE_NAME = api_name
    API_VERSION = api_version
    SCOPES = [scope for scope in scopes[0]]
    
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json',SCOPES)
    if not creds or creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json',SCOPES)
            creds = flow.run_local_server(port=0)
        with open ('token.json','w') as token:
            token.write(creds.to_json())

    try: 
        service = build(CLIENT_SECRET_FILE,API_SERVICE_NAME,API_VERSION,credentials=creds)
        return service
    except HTTPError as error:
        print('err',error)
                                
from google_apis import create_service
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

CLIENT_SECRET_FILE = 'credentials.json'
API_NAME = 'gmail'
API_VERSION = 'v1'
SCOPES = ['https://mail.google.com/']

service = create_service(CLIENT_SECRET_FILE,API_NAME,API_VERSION,SCOPES)

emailMsg = "I don't know"
mimeMessage = MIMEMultipart()
mimeMessage['to'] = 'tstudystuff@gmail.com'
mimeMessage['subject'] = "I'm gonna start drinking I think,"
mimeMessage.attach(MIMEText(emailMsg,'plain'))
raw_string = base64.urlsafe_b64encode(mimeMessage.as_bytes()).decode('utf-8')

message = service.users().messages().send(userId='me', body={'raw': raw_string}).execute()