🚀 Executive Summary

TL;DR: Manual vendor onboarding, involving repetitive Google Drive folder creation and email sending, consumes significant time. This Python script automates the entire process by programmatically creating dedicated Google Drive folders and dispatching welcome emails with necessary forms via Google Drive and Gmail APIs, saving valuable time.

🎯 Key Takeaways

  • Leverage service accounts with domain-wide delegation for Google Workspace automation to ensure security and allow email sending on behalf of a user.
  • Manage sensitive configuration data using `config.env` and `python-dotenv` to avoid hardcoding secrets and improve maintainability.
  • Implement error handling and pre-checks, such as verifying API scopes and checking for existing folders, to create a robust and fault-tolerant automation script.

Automate Vendor Onboarding: Send Forms and Create Folder

Automate Vendor Onboarding: Send Forms and Create Folder

Hey team, Darian here. Let’s talk about a classic time-sink: vendor onboarding. I used to manually create a Google Drive folder, find the link to our standard NDA and W-9 forms, draft a welcome email, and send it off. For every. single. vendor. I calculated it once—I was losing about 90 minutes a week to this repetitive task. That’s 90 minutes I could have spent optimizing our CI/CD pipelines or, you know, having a coffee.

This tutorial will walk you through the exact Python script I built to automate that entire workflow. You’ll give it a vendor name and email, and it will create a dedicated Google Drive folder and send them a welcome email with the necessary forms. It’s a simple, high-impact automation that gives you back valuable time.

Prerequisites

Before we dive in, make sure you have the following ready:

  • A Google Workspace account with admin access to create API credentials.
  • Python 3 installed on your system.
  • A Google Cloud Platform project with the Google Drive API and Gmail API enabled.
  • The vendor’s name and contact email.

The Guide: Step-by-Step

Step 1: Project Setup and Dependencies

First, get your project directory organized. I typically have a main script file, say onboard_vendor.py, and a configuration file named config.env to hold our secrets. I’ll skip the standard virtualenv setup since you likely have your own workflow for that. Just make sure you install the necessary libraries. In your terminal, you’ll need to run the pip install commands for google-api-python-client, google-auth-httplib2, google-auth-oauthlib, and python-dotenv. It’s a good practice to manage these in a requirements.txt file.

Pro Tip: I strongly recommend using a service account for this automation. It doesn’t rely on your personal user credentials, so it won’t break if you change your password or leave the company. Download the JSON key file from the Google Cloud Console and save it securely in your project directory.

Step 2: Configuration and Authentication

Let’s not hardcode secrets. It’s a security risk and a pain to update. Create a file named config.env in your project root.

# config.env
PARENT_FOLDER_ID="YOUR_MAIN_VENDORS_FOLDER_ID_HERE"
SERVICE_ACCOUNT_FILE="your-credentials-file.json"
SENDER_EMAIL="automation@techresolve.com"
FORM_LINK="https://docs.google.com/document/d/YOUR_FORM_LINK_HERE"

Now, let’s write the Python code to handle authentication. This part of the script will load our configuration and establish a connection to the Google services.

# onboard_vendor.py
import os
import base64
from email.mime.text import MIMEText
from dotenv import load_dotenv
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Load environment variables from config.env
load_dotenv('config.env')

# Configuration
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/gmail.send']
SERVICE_ACCOUNT_FILE = os.getenv('SERVICE_ACCOUNT_FILE')
PARENT_FOLDER_ID = os.getenv('PARENT_FOLDER_ID')
SENDER_EMAIL = os.getenv('SENDER_EMAIL')
FORM_LINK = os.getenv('FORM_LINK')

def get_google_services():
    """Authenticates and returns Drive and Gmail service objects."""
    creds = None
    try:
        creds = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)
        
        # We need to delegate authority to the service account for Gmail
        delegated_creds = creds.with_subject(SENDER_EMAIL)

        drive_service = build('drive', 'v3', credentials=creds)
        gmail_service = build('gmail', 'v1', credentials=delegated_creds)
        return drive_service, gmail_service
    except Exception as e:
        print(f"Authentication failed: {e}")
        return None, None

Notice the with_subject method. For a service account to send email on behalf of a user, you must grant it domain-wide delegation in your Google Workspace admin console. This is a critical step.

Step 3: Creating the Google Drive Folder

Next, let’s write the function that creates the folder. It’s straightforward: we define the folder’s metadata (name and parent) and then execute the create request.

def create_vendor_folder(drive_service, vendor_name):
    """Creates a new folder for the vendor in Google Drive."""
    folder_metadata = {
        'name': vendor_name,
        'mimeType': 'application/vnd.google-apps.folder',
        'parents': [PARENT_FOLDER_ID]
    }
    try:
        folder = drive_service.files().create(body=folder_metadata, fields='id').execute()
        print(f"Successfully created folder: {vendor_name} with ID: {folder.get('id')}")
        return folder.get('id')
    except HttpError as error:
        print(f"An error occurred while creating the folder: {error}")
        return None

Pro Tip: Add error handling to check if a folder with that name already exists. In my production setups, I first run a search query (drive_service.files().list()) to prevent creating duplicate folders if the script is run twice by accident.

Step 4: Sending the Onboarding Email

Now for the email. We’ll compose a standard welcome message using Python’s `MIMEText` and then use the Gmail API to send it. The message is base64 encoded, which is a requirement for the API.

def send_onboarding_email(gmail_service, vendor_name, vendor_email):
    """Sends a welcome email with the forms link to the vendor."""
    subject = f"Welcome to TechResolve, {vendor_name}!"
    body = f"""
    Hi {vendor_name},

    Welcome aboard! We're excited to partner with you.

    To get started, please complete the necessary onboarding forms which can be found at the link below:
    {FORM_LINK}

    We have created a shared folder for our collaboration. Let us know if you have any questions.

    Best,
    The TechResolve Team
    """
    
    try:
        message = MIMEText(body)
        message['to'] = vendor_email
        message['from'] = SENDER_EMAIL
        message['subject'] = subject
        
        encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
        create_message = {'raw': encoded_message}

        send_message = (gmail_service.users().messages().send(userId="me", body=create_message).execute())
        print(f"Email sent successfully to {vendor_email}. Message ID: {send_message['id']}")
        return True
    except HttpError as error:
        print(f"An error occurred while sending the email: {error}")
        return False

Step 5: Bringing It All Together

Finally, let’s create a main function to orchestrate the entire workflow. This function will call our other functions in the correct order.

def onboard_new_vendor(vendor_name, vendor_email):
    """Main function to run the complete vendor onboarding process."""
    print(f"Starting onboarding for {vendor_name} ({vendor_email})...")
    
    drive_service, gmail_service = get_google_services()
    
    if not drive_service or not gmail_service:
        print("Could not connect to Google services. Aborting.")
        return

    # Step 1: Create the folder
    folder_id = create_vendor_folder(drive_service, vendor_name)
    if not folder_id:
        print("Failed to create folder. Aborting email send.")
        return

    # Step 2: Send the email
    email_sent = send_onboarding_email(gmail_service, vendor_name, vendor_email)
    if email_sent:
        print(f"Onboarding for {vendor_name} completed successfully.")
    else:
        print(f"Onboarding for {vendor_name} failed at the email step.")

if __name__ == '__main__':
    # Example usage
    new_vendor_name = "SecureScan Solutions"
    new_vendor_email = "contracts@securescan.example.com"
    onboard_new_vendor(new_vendor_name, new_vendor_email)

Common Pitfalls

Here are a few places where I’ve stumbled in the past, so you can avoid them:

  • Incorrect API Scopes: Forgetting a scope in the SCOPES list is the most common error. If you get a “permission denied” error, double-check that you have included both the Drive and Gmail scopes.
  • Domain-Wide Delegation: The service account can’t send emails on behalf of a user without you explicitly granting it permission in the Google Workspace Admin console. If your email step fails, this is the first place I’d look.
  • Invalid Parent Folder ID: Copying the wrong ID for your main “Vendors” folder will cause the script to fail. The ID is the long string of characters in the URL when you have the folder open in Google Drive.

Conclusion

And there you have it. A robust, automated workflow that takes a repetitive task off your plate. You can easily extend this script to read from a CSV file or a simple web form to onboard vendors in bulk. In my day-to-day, I have this hooked up to a small internal tool, so our procurement team can trigger it without ever touching a line of code. It’s a prime example of how a little bit of scripting can deliver a huge boost in efficiency and consistency.

Darian Vance - Lead Cloud Architect

Darian Vance

Lead Cloud Architect & DevOps Strategist

With over 12 years in system architecture and automation, Darian specializes in simplifying complex cloud infrastructures. An advocate for open-source solutions, he founded TechResolve to provide engineers with actionable, battle-tested troubleshooting guides and robust software alternatives.


🤖 Frequently Asked Questions

âť“ How can I automate vendor onboarding using Google Drive and Gmail APIs?

You can automate vendor onboarding by developing a Python script that utilizes the `google-api-python-client` library. This script authenticates with a service account, creates a dedicated Google Drive folder for each vendor using the Drive API, and sends a personalized welcome email with form links via the Gmail API, leveraging domain-wide delegation.

âť“ How does this Python automation compare to manual vendor onboarding processes?

This Python automation significantly reduces the time and effort associated with manual vendor onboarding, eliminating repetitive tasks like folder creation and email drafting. It ensures consistency, minimizes human error, and frees up valuable time for more strategic work, offering a substantial boost in efficiency compared to manual methods.

âť“ What is a common implementation pitfall when setting up Google Workspace API automation for email sending?

A common pitfall is failing to grant domain-wide delegation to the service account in the Google Workspace Admin console. Without this explicit permission, the service account cannot send emails on behalf of a user, leading to ‘permission denied’ errors during the email sending step.

Leave a Reply

Discover more from TechResolve - SaaS Troubleshooting & Software Alternatives

Subscribe now to keep reading and get access to the full archive.

Continue reading