如何在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:
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.jsonfor simplicity. - Upload this file to your Colab notebook’s file system (use the file upload button in the left sidebar’s "Files" section).
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
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
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")
- 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.jsonfile 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.jsonortoken.jsonfiles—they grant access to send emails from your account.
内容的提问来源于stack exchange,提问作者Pankaj Shinde

