Skip to content

Instantly share code, notes, and snippets.

Created February 19, 2024 13:13
Show Gist options
  • Save SohaibAnwaar/65e49e8c9b077cd5f4bd64ae5e25925d to your computer and use it in GitHub Desktop.
Save SohaibAnwaar/65e49e8c9b077cd5f4bd64ae5e25925d to your computer and use it in GitHub Desktop.
Create Gmail Draft
# Draft Email on you Gmail Account
## Author: Sohaib Anwaaar
### Description:
Create Email Draft in your gmail account
### Create Credentials.json
To create your Credentials.json file for accessing Google APIs, follow these steps:
1. Sign in to your Google account.
2. Navigate to the Google Cloud Console by clicking on this link: [Google Cloud Console](
3. Click on the "Create credentials" button.
4. Select "OAuth client ID" from the dropdown menu.
5. Choose "Desktop app" as the application type.
6. Click on the "Create" button to generate your OAuth 2.0 client ID.
7. Your Credentials.json file will be automatically downloaded.
8. Save the downloaded file to your project directory.
Now you can use the Credentials.json file to authenticate your application and access Google APIs.
import os
import pickle
import base64
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['']
def main():
Main function to create a draft email using the Gmail API.
creds = None
# Load or refresh user credentials
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_console()
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
# Build the Gmail service
service = build('gmail', 'v1', credentials=creds)
# Define the email message content
email_content = """
Subject: Subject line here
Email body here.
# Create a draft email
create_draft(service, 'me', email_content)
def create_draft(service, user_id, message_body):
Create a draft email.
service: Gmail service instance.
user_id: User ID.
message_body: Content of the email message.
# Encode the email content in Base64 format
encoded_content = base64.urlsafe_b64encode(message_body.encode()).decode()
# Define the draft message
message = {'message': {'raw': encoded_content}}
# Create the draft
draft = service.users().drafts().create(userId=user_id, body=message).execute()
print('Draft created: %s' % draft['id'])
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment