Skip to content

guberm/gmail-telegram-bot-csharp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

28 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Telegram Gmail Integration Bot

.NET Build .NET License

A .NET 8 console application that integrates Gmail with Telegram using OAuth 2.0 authentication. Each user authenticates their own Gmail account through the bot, which then forwards new inbox messages to their Telegram chat with interactive action buttons.

🌟 Key Features

  • πŸ” OAuth 2.0 Authentication - Per-user Gmail authentication via web flow
  • πŸ“¨ Email Forwarding - Automatically forwards new inbox messages to Telegram
  • πŸŽ›οΈ Interactive Buttons - Delete, Archive, Star, and Forward actions
  • 🏷️ Label Management - View and modify Gmail labels
  • πŸ’Ύ SQLite Persistence - Stores messages, actions, and user credentials
  • πŸ”„ Automatic Token Refresh - Handles expired access tokens seamlessly
  • πŸ”— Direct Links - Quick access to open emails in Gmail
  • πŸ“Š Action History - Tracks all user actions on messages
  • πŸ›‘οΈ CSRF Protection - Secure OAuth state validation
  • ⚑ Resilient Polling - Retries with exponential backoff

πŸš€ Quick Start

Prerequisites

Installation

# Clone the repository
git clone https://github.com/guberm/gmail-telegram-bot-csharp.git
cd gmail-telegram-bot-csharp

# Restore dependencies
dotnet restore

# Copy settings template
cp settings.json.template settings.json  # Linux/Mac
copy settings.json.template settings.json  # Windows

Configuration

  1. Create Google OAuth Credentials

    • Go to Google Cloud Console
    • Enable Gmail API
    • Create OAuth 2.0 Client ID (Web application)
    • Add redirect URI: http://localhost:8080/oauth/callback
    • Copy the Client ID and Client Secret
  2. Get Telegram Bot Token

    • Message @BotFather on Telegram
    • Create a new bot with /newbot
    • Copy the bot token
  3. Update settings.json

{
  "telegram_bot_token": "YOUR_BOT_TOKEN_FROM_BOTFATHER",
  "google_client_id": "YOUR_GOOGLE_CLIENT_ID",
  "google_client_secret": "YOUR_GOOGLE_CLIENT_SECRET",
  "polling_interval_seconds": 60,
  "database_path": "telegram_gmail.db",
  "gmail_scopes": [
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.modify"
  ],
  "oauth_callback_url": "http://localhost:8080/oauth/callback",
  "oauth_callback_port": 8080,
  "application_name": "Telegram Gmail Bot"
}

Important:

  • ⚠️ Never commit settings.json to version control
  • πŸ” Each user authenticates individually - no shared credentials
  • πŸ“š See OAUTH_SETUP.md for detailed setup instructions

Running the Bot

dotnet run

The bot will:

  1. βœ… Validate configuration (Telegram token + Google OAuth credentials)
  2. πŸ—„οΈ Initialize SQLite database
  3. 🌐 Start OAuth callback server on port 8080
  4. πŸ€– Start Telegram bot
  5. ⏳ Wait for users to authenticate via /start command

🎯 User Guide

Authentication Flow

  1. Start the bot - Send /start to your bot on Telegram
  2. Click the OAuth link - Bot responds with "πŸ” Connect Gmail Account" button
  3. Authorize on Google - Grant Gmail permissions in your browser
  4. Success! - You'll be redirected and the bot confirms connection
  5. Receive emails - New Gmail messages appear in your Telegram chat

Available Commands

Command Description
/start Connect your Gmail account via OAuth authentication
/status Check your Gmail connection status and details
/disconnect Revoke access and delete stored credentials
/help Show available commands and detailed usage guide

Email Actions

Each forwarded email includes inline buttons:

  • πŸ—‘οΈ Delete - Move email to trash
  • πŸ“¦ Archive - Remove from inbox (keep in All Mail)
  • ⭐ Star - Add star to email
  • ➑️ Forward - Forward email to another address (coming soon)

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”     OAuth Link      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Telegram  │◄──────────────────►│ Google OAuth β”‚
β”‚   Bot     β”‚                    β”‚   Server    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚                                   β”‚
       β”‚ Token Callback                    β”‚ Auth Code
       β”‚β—„β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β”‚ Store Credentials (SQLite)
       β”‚
       β”‚ Fetch Emails (Gmail API)
       β”‚
       β”‚ Forward to User (Telegram)

Database Schema

user_credentials

Stores OAuth tokens per user

chat_id, access_token, refresh_token, expires_at, created_at, updated_at, email_address

oauth_states

CSRF protection for OAuth flow

state, chat_id, created_at, expires_at

messages

Email message cache

message_id, subject, sender, received_datetime, content, attachments, labels, direct_link, is_read, telegram_message_id

actions

User action history

id, message_id, action_type, action_timestamp, user_id, new_label_values

πŸ”’ Security Features

  • πŸ‘€ Per-user OAuth - No shared credentials
  • πŸ›‘οΈ CSRF Protection - Random state validation
  • πŸ” Token Encryption - Secure storage in SQLite
  • πŸ”„ Automatic Refresh - Expired tokens handled transparently
  • 🚫 User Revocation - Users can disconnect anytime
  • ⏰ State Expiration - OAuth states expire after 10 minutes

πŸ“š Documentation

πŸ› οΈ Development

Building

dotnet build -c Release

Running Tests

dotnet test

Project Structure

gmail-telegram-bot-csharp/
β”œβ”€β”€ Models/              # Data models
β”‚   β”œβ”€β”€ AppSettings.cs
β”‚   β”œβ”€β”€ UserCredentials.cs
β”‚   └── OAuthState.cs
β”œβ”€β”€ Services/            # Business logic
β”‚   β”œβ”€β”€ OAuthService.cs
β”‚   β”œβ”€β”€ OAuthCallbackServer.cs
β”‚   β”œβ”€β”€ GmailClient.cs
β”‚   └── TelegramBotService.cs
β”œβ”€β”€ DatabaseService.cs   # SQLite persistence
β”œβ”€β”€ Program.cs           # Entry point
└── tests/               # Unit tests

πŸ—ΊοΈ Roadmap

  • Complete Forward implementation - Send emails to other addresses
  • Multi-account support - Multiple Gmail accounts per user
  • Enhanced label management - Advanced label operations
  • Attachment handling - Download and send attachments via Telegram
  • Search functionality - Search emails via bot commands
  • Email composition - Send new emails from Telegram
  • Filters & Rules - Custom email filtering rules
  • Notification customization - Per-user notification preferences
  • Web dashboard - Optional web interface for management

🀝 Contributing

Contributions are welcome! Please see CONTRIBUTING.md for:

  • Code style guidelines
  • Pull request process
  • Development setup
  • Testing requirements

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

πŸ’¬ Support


⚠️ Security Note: Never commit settings.json, telegram_gmail.db, or any files containing credentials to version control!

About

Telegram + Gmail integration bot in C# (.NET 8) forwarding emails to Telegram with action controls.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages