You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Colab数据处理任务完成时发送Gmail邮件通知?

Got it, let's walk through how to set up automatic Gmail notifications when your Colab data processing task finishes. I’ve implemented this for several of my own workflows, so here’s a reliable, step-by-step solution that works every time:

Step 1: Set Up Gmail API Credentials

First, you need to let Colab access your Gmail account securely via the Gmail API. Here’s how:

  • Head to the Google Cloud Console, create a new project (name it something like "Colab Task Notifications").
  • Search for "Gmail API" in the API library, then enable it for your project.
  • Go to the "Credentials" tab, click "Create Credentials" > "OAuth client ID".
  • Select "Desktop app" as the application type, give it a name, then download the JSON file that pops up. Rename this file to credentials.json for simplicity.
  • Upload this file to your Colab notebook’s file system (use the file upload button in the left sidebar’s "Files" section).
Step 2: Install Required Libraries

Colab doesn’t come with all the Google API tools pre-installed, so run this command to get the necessary packages:

!pip install --upgrade google-auth google-auth-oauthlib google-api-python-client
Step 3: Write the Email Notification Function

This function handles authentication, creates your email, and sends it via the Gmail API. Copy this into your notebook:

import os
import base64
from email.mime.text import MIMEText
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Scope only allows sending emails—no full Gmail access
SCOPES = ['https://www.googleapis.com/auth/gmail.send']

def send_gmail_notification(subject, body, to_email):
    creds = None
    # Token.json stores your access/refresh tokens (auto-created after first auth)
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    
    # Refresh or re-authenticate if needed
    if not creds or not 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)
        # Save token for next runs
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        # Connect to Gmail API
        service = build('gmail', 'v1', credentials=creds)
        # Build the email
        message = MIMEText(body)
        message['to'] = to_email
        message['subject'] = subject
        # Encode message for Gmail API
        encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()

        send_request = {'raw': encoded_message}
        # Send the email
        sent_message = service.users().messages().send(userId='me', body=send_request).execute()
        print(f"Notification sent! Message ID: {sent_message['id']}")
    except HttpError as error:
        print(f"Failed to send notification: {error}")
        sent_message = None
    return sent_message
Step 4: Integrate with Your Data Processing Task

Now tie the notification function to your actual task. Use a try-except block to handle success, warnings, or failures:

def run_your_data_processing():
    # Replace this with your actual data processing code
    print("Starting data processing...")
    # Example: simulate a long-running task
    import time
    time.sleep(15)
    # If your task has checks for warnings, add them here
    print("Data processing done!")
    return True

# Execute task and send notification
try:
    task_success = run_your_data_processing()
    if task_success:
        email_subject = "Colab Update: Data Processing Completed Successfully!"
        email_body = """Hi there,

Your data processing task in Colab has finished running without any issues.

Best regards,
Your Colab Task Bot"""
    else:
        email_subject = "Colab Update: Data Processing Completed with Warnings"
        email_body = """Hi there,

Your data processing task finished, but there were some warnings to review.

Best regards,
Your Colab Task Bot"""
except Exception as e:
    email_subject = "Colab Alert: Data Processing Failed!"
    email_body = f"""Hi there,

Your data processing task failed with the following error:

{str(e)}

Best regards,
Your Colab Task Bot"""

# Replace with your email address
send_gmail_notification(email_subject, email_body, "your-email@example.com")
Key Tips to Remember
  • First-time run: You’ll get a login prompt (click the link, log in with your Google account). You’ll see a "Google hasn’t verified this app" warning—this is normal for your own personal app. Click "Advanced" > "Go to [Your App Name]" to grant permission.
  • Token persistence: The token.json file will be saved in Colab, so subsequent runs won’t require re-authenticating (as long as the token is valid).
  • Security: Never share your credentials.json or token.json files—they grant access to send emails from your account.

内容的提问来源于stack exchange,提问作者Pankaj Shinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:47:47