A modern Python 3 library for interacting with Gmail using IMAP and SMTP protocols.
- Python 3.8+ - Fully modernized for Python 3
- Type hints - Complete type annotations for better IDE support
- OAuth2 support - Secure authentication using OAuth2 tokens
- Context managers - Automatic resource cleanup
- Error handling - Specific exceptions for different error types
- Modern email API - Uses the latest email.policy for better RFC compliance
- Gmail search - Support for Gmail's advanced search syntax
pip install gmaillibgit clone https://github.com/thedjpetersen/gmaillib.git
cd gmaillib
pip install -e .import gmaillib
# Initialize account with password
account = gmaillib.Account('your-email@gmail.com', password='your-password')
# Get inbox messages
messages = account.inbox()
for msg in messages:
print(f"From: {msg.sender_addr}")
print(f"Subject: {msg.subject}")
# Clean up
account.exit_server()import gmaillib
# Automatic cleanup with context manager
with gmaillib.Account('your-email@gmail.com', password='your-password') as account:
messages = account.inbox()
for msg in messages:
print(f"From: {msg.sender_addr}")import gmaillib
# Initialize with OAuth2 token
account = gmaillib.Account(
'your-email@gmail.com',
oauth2_token='your-oauth2-access-token'
)
messages = account.unread()
account.exit_server()with gmaillib.Account('email@gmail.com', password='pass') as account:
# Get 10 messages starting from position 0
messages = account.inbox(start=0, amount=10)
# Get next 10 messages
messages = account.inbox(start=10, amount=10)with gmaillib.Account('email@gmail.com', password='pass') as account:
unread = account.unread()
print(f"You have {len(unread)} unread messages")with gmaillib.Account('email@gmail.com', password='pass') as account:
count = account.get_inbox_count()
print(f"Total messages: {count}")with gmaillib.Account('email@gmail.com', password='pass') as account:
all_messages = account.get_all_messages()Use Gmail's advanced search syntax:
with gmaillib.Account('email@gmail.com', password='pass') as account:
# Search by sender
messages = account.filter('from:someone@example.com')
# Search by subject
messages = account.filter('subject:important')
# Complex search
messages = account.filter('from:boss@company.com subject:urgent after:2024/01/01')
# Search with labels
messages = account.filter('label:work is:unread')with gmaillib.Account('email@gmail.com', password='pass') as account:
account.send(
toaddr='recipient@example.com',
subject='Hello',
msg='This is a plain text message'
)with gmaillib.Account('email@gmail.com', password='pass') as account:
html_content = '''
<html>
<body>
<h1>Hello!</h1>
<p>This is an <strong>HTML</strong> email.</p>
</body>
</html>
'''
account.send(
toaddr='recipient@example.com',
subject='HTML Email',
msg=html_content,
html=True
)with gmaillib.Account('email@gmail.com', password='pass') as account:
messages = account.inbox(amount=5)
for msg in messages:
# Download attachments to a directory
result = msg.download_attachment('/path/to/save/directory')
print(result)with gmaillib.Account('email@gmail.com', password='pass') as account:
messages = account.inbox(amount=1)
msg = messages[0]
# Access message properties
print(f"From: {msg.sender_addr}")
print(f"To: {msg.receiver_addr}")
print(f"Date: {msg.date}")
print(f"Subject: {msg.subject}")
print(f"Body: {msg.body}")
# Get HTML content
html_messages = gmaillib.Message(msg.parsed_email, types=['text/html'])
print(html_messages.body)import gmaillib
from gmaillib import AuthenticationError, ConnectionError, MessageError
try:
with gmaillib.Account('email@gmail.com', password='wrong-password') as account:
messages = account.inbox()
except AuthenticationError as e:
print(f"Authentication failed: {e}")
except ConnectionError as e:
print(f"Connection failed: {e}")
except MessageError as e:
print(f"Message operation failed: {e}")with gmaillib.Account('email@gmail.com', password='pass') as account:
# Create a new mailbox/label
account.create_mailbox('MyNewLabel')
# Append a message to a mailbox
account.append(
mailbox='MyNewLabel',
flags='\\Seen',
date_time=None,
message='email content here'
)Initialize a Gmail account connection.
Parameters:
username(str): Gmail email addresspassword(str, optional): Account password for basic authoauth2_token(str, optional): OAuth2 access token (recommended)
Raises:
AuthenticationError: If authentication failsConnectionError: If connection to Gmail servers fails
inbox(start=0, amount=10)- Get a range of inbox messagesunread()- Get all unread messagesget_all_messages()- Get all inbox messagesget_inbox_count()- Get total number of inbox messagessend(toaddr, subject='', msg='', html=False)- Send an emailfilter(search_string)- Search emails using Gmail syntaxcreate_mailbox(mailbox)- Create a new mailbox/labelappend(mailbox, flags, date_time, message)- Append message to mailboxexit_server()- Close all connections
Represents an email message.
Parameters:
fetched_email(str or bytes): Raw email datatypes(list, optional): Acceptable content types (default: ['text/plain'])
parsed_email- The parsed email message objectreceiver_addr- Email address of the receiversender_addr- Email address of the senderdate- Date the message was sentsubject- Subject of the emailbody- Content of the email
download_attachment(dest_dir)- Download attachments to directory
If you're upgrading from the Python 2 version, here are the key changes:
# Old (Python 2)
import gmaillib
account = gmaillib.account('email', 'pass') # lowercase 'account'
# New (Python 3)
import gmaillib
account = gmaillib.Account('email', password='pass') # capitalized, keyword argsFor minimal code changes, lowercase aliases are available:
import gmaillib
account = gmaillib.account('email', 'pass') # Still works!
msg = gmaillib.message(email_data) # Still works!- Print statements →
print()functions - String handling - Proper bytes/str handling for Python 3
- Email parsing - Uses modern
email.policy.default - Context managers - Use
withstatements for auto cleanup - Type hints - Better IDE support and code documentation
- OAuth2 - Secure authentication support
- Error handling - Specific exception types
- Python 3.8 or higher
- No external dependencies (uses stdlib only)
If using password authentication with 2FA enabled, you'll need to generate an App Password:
- Go to your Google Account
- Select Security
- Under "Signing in to Google," select App Passwords
- Generate a new app password for "Mail"
- Use this password instead of your regular password
For production applications, use OAuth2 authentication:
- Set up a project in Google Cloud Console
- Enable the Gmail API
- Create OAuth2 credentials
- Get an access token
- Pass the token to
Account(oauth2_token=...)
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run with coverage
pytest --cov=gmaillib# Format code
black gmaillib.py
# Lint code
ruff check gmaillib.py
# Type checking
mypy gmaillib.pyMIT License - Copyright (c) 2013-2024 David Petersen
See LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
- Original library by David Petersen
- Inspired by this excellent blog post
- Contributors: See GitHub contributors page
- Breaking: Python 3.8+ required (dropped Python 2 support)
- New: OAuth2 authentication support
- New: Context manager support
- New: Type hints throughout
- New: Specific exception types
- Improved: Modern email parsing with email.policy
- Improved: Better bytes/string handling
- Improved: HTML email support in send()
- Improved: Better error messages
- Fixed: All Python 3 compatibility issues
- Initial release
- Python 2 support
- Basic IMAP/SMTP functionality