A Python-based system that transfers emails from Gmail to any IMAP server while preserving folder structure, metadata, and content. Features progress tracking and resumable transfers.
- OAuth 2.0 Authentication: Secure Gmail access without storing passwords
- Progress Tracking: Resume interrupted transfers from last checkpoint
- Folder Mapping: Automatically maps Gmail labels to IMAP folders
- Metadata Preservation: Preserves read/unread status, flags, and timestamps
- Duplicate Detection: Skips already transferred emails
- Error Recovery: Automatic retry mechanism with exponential backoff
- Progress Reporting: Real-time progress bars and detailed logging
- Python 3.8 or higher
- Gmail account with API access enabled
- Target IMAP server credentials
-
Clone or download this project
git clone <repository-url> cd gmail_to_imap
-
Create a virtual environment (recommended)
python -m venv gmail_to_imap_env source gmail_to_imap_env/bin/activate # On Windows: gmail_to_imap_env\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Enable the Gmail API:
- Go to "APIs & Services" > "Library"
- Search for "Gmail API" and enable it
- Add the gmail accounts you'll migrate as your test users
- Go to "APIs & Services" > "Credentials"
- Click "Create Credentials" > "OAuth client ID"
- Choose "Web application"
- In redirect Url put http://localhost:8085
- Download the credentials JSON file
- Rename it to
credentials.json
and place it in the project directory
- Go to "APIs & Services" > "OAuth consent screen"
- Choose "External" (unless you have Google Workspace)
- Fill in the required fields (app name, user support email, etc.)
- Add your email to test users in development mode
-
Copy and edit the configuration file
cp config_sample.yaml config.yaml
-
Edit
config.yaml
with your settingsgmail: credentials_file: "credentials.json" imap: server: "your-imap-server.com" # e.g., "imap.example.com" port: 993 # Usually 993 for SSL, 143 for non-SSL username: "your-email@domain.com" password: "your-imap-password" use_ssl: true settings: batch_size: 50 # Adjust based on server limits max_retries: 3 resume_from_progress: true # Customize label mappings as needed label_mappings: "INBOX": "INBOX" "SENT": "Sent" "DRAFT": "Drafts" "SPAM": "Junk" "TRASH": "Trash"
python gmail_to_imap.py
python gmail_to_imap.py --config my_config.yaml
python gmail_to_imap.py --verbose
--config
: Specify custom configuration file (default:config.yaml
)--verbose
,-v
: Enable verbose logging--help
,-h
: Show help message
-
Prepare your configuration
- Ensure
credentials.json
is in the project directory - Update
config.yaml
with your IMAP server details
- Ensure
-
Run the transfer
python gmail_to_imap.py
-
Complete OAuth flow
- A browser window will open for Gmail authentication
- Grant the necessary permissions
- The browser will show a success message
- Return to the terminal to see the transfer progress
-
Monitor progress
- Progress is displayed with real-time progress bars
- Detailed logs are written to
gmail_to_imap.log
- Progress is saved to
progress.json
for resumability
gmail_to_imap/
├── gmail_to_imap.py # Main application
├── config.yaml # Configuration template
├── credentials.json # Gmail OAuth credentials (you provide)
├── token.json # OAuth token (auto-generated)
├── progress.json # Progress tracking (auto-generated)
├── gmail_to_imap.log # Application logs (auto-generated)
├── requirements.txt # Python dependencies
└── README.md # This file
The system automatically tracks progress in progress.json
. If the transfer is interrupted:
- Automatic Resume: Simply run the command again
- Skip Completed: Already transferred emails are automatically skipped
- Progress Display: Shows completion status for each label/folder
{
"session_id": "2024-01-15_12-30-45",
"total_labels": 5,
"completed_labels": 2,
"current_label": "INBOX",
"transferred_messages": {
"INBOX": ["message_id_1", "message_id_2"],
"SENT": ["message_id_3"]
},
"label_folder_mapping": {
"INBOX": "INBOX",
"SENT": "Sent"
}
}
credentials_file
: Path to Gmail OAuth credentials JSON file
server
: IMAP server hostnameport
: IMAP server port (993 for SSL, 143 for non-SSL)username
: IMAP username/emailpassword
: IMAP passworduse_ssl
: Enable SSL/TLS encryption (recommended:true
)
batch_size
: Number of emails to process per batch (default: 50)max_retries
: Maximum retry attempts for failed operations (default: 3)resume_from_progress
: Enable resumable transfers (default:true
)label_mappings
: Custom mapping from Gmail labels to IMAP folder names
-
Authentication Error
Error: Gmail credentials file 'credentials.json' not found
Solution: Download OAuth credentials from Google Cloud Console
-
IMAP Connection Failed
Error: Failed to connect to IMAP server
Solutions:
- Verify server hostname and port
- Check username and password
- Ensure IMAP is enabled on the target server
- Check firewall settings
-
Gmail API Quota Exceeded
Error: Quota exceeded for quota metric 'Queries' and limit 'Queries per day'
Solution: Wait for quota reset (usually 24 hours) or request quota increase
-
SSL Certificate Error
Error: SSL certificate verification failed
Solution: Check server SSL configuration or temporarily set
use_ssl: false
for testing
Enable verbose logging for detailed troubleshooting:
python gmail_to_imap.py --verbose
Check gmail_to_imap.log
for detailed operation logs:
tail -f gmail_to_imap.log
- Adjust Batch Size: Increase
batch_size
for faster transfers (but watch for memory usage) - Network Stability: Ensure stable internet connection for large transfers
- IMAP Server Limits: Some servers have rate limits; adjust
batch_size
accordingly - Resume Strategy: For very large transfers, run in smaller chunks and resume as needed
- Credential Storage: Keep
credentials.json
andconfig.yaml
secure - OAuth Tokens:
token.json
contains sensitive data - don't share it - IMAP Passwords: Consider using app-specific passwords where available
- Network Security: Always use SSL/TLS for IMAP connections
- Gmail API Limits: Subject to Google's API quotas and rate limits
- IMAP Server Limits: Performance depends on target IMAP server capabilities
- Large Attachments: Very large emails might require special handling
- Special Characters: Some folder names with special characters might need manual mapping
For issues and questions:
- Check this README and troubleshooting section
- Review the log files for error details
- Verify your configuration settings
- Test with a small subset of emails first
This project is provided as-is for educational and personal use. Please ensure compliance with Gmail's Terms of Service and your IMAP provider's policies.