A Python package for sending emails using Gmail SMTP
Project description
MailWorks
A Python package for sending emails using Gmail's SMTP server. This package provides a simple, secure, and reliable way to send emails through Gmail with support for HTML content, attachments, and multiple recipients.
Features
- ✅ Send emails via Gmail SMTP
- ✅ Support for plain text and HTML emails
- ✅ File attachments
- ✅ Multiple recipients
- ✅ Environment variable configuration
- ✅ Configuration file support
- ✅ Connection testing
- ✅ Comprehensive error handling
- ✅ No external dependencies (uses Python standard library only)
Installation
From source (development)
# Clone the repository
git clone https://github.com/antoniocostabr/mailworks.git
cd mailworks
# Install in development mode
pip install -e .
# Or install with development dependencies
pip install -e ".[dev]"
From PyPI (when published)
pip install mailworks
Gmail Setup
Before using this package, you need to set up Gmail App Passwords:
Step 1: Enable 2-Factor Authentication
- Go to Google Account settings
- Navigate to "Security" > "2-Step Verification"
- Enable 2-Step Verification if not already enabled
Step 2: Generate App Password
- Go to Google Account settings
- Navigate to "Security" > "2-Step Verification" > "App passwords"
- Select "Mail" and your device
- Generate the app password
- Important: Use this 16-character app password, not your regular Gmail password
Quick Start
Basic Usage
from email_sender import GmailSender
# Method 1: Using environment variables
# Set environment variables:
# export GMAIL_EMAIL="your.email@gmail.com"
# export GMAIL_PASSWORD="your_app_password"
sender = GmailSender()
# Send a simple email
success = sender.send_simple_email(
to_email="recipient@example.com",
subject="Hello from Python!",
message="This is a test email sent from Python."
)
if success:
print("Email sent successfully!")
Advanced Usage
from email_sender import GmailSender
# Method 2: Direct credentials
sender = GmailSender(
email="your.email@gmail.com",
password="your_app_password"
)
# Send HTML email with attachments to multiple recipients
success = sender.send_email(
to_emails=["recipient1@example.com", "recipient2@example.com"],
subject="Advanced Email Example",
message="Plain text version of the email.",
html_message="""
<html>
<body>
<h2>Hello!</h2>
<p>This is an <b>HTML email</b> with formatting.</p>
</body>
</html>
""",
attachments=["document.pdf", "image.png"]
)
Configuration Options
1. Environment Variables
Set these environment variables:
export GMAIL_EMAIL="your.email@gmail.com"
export GMAIL_PASSWORD="your_app_password"
export GMAIL_SMTP_SERVER="smtp.gmail.com" # Optional
export GMAIL_SMTP_PORT="587" # Optional
2. Configuration File
Create a config file (e.g., gmail_config.txt):
GMAIL_EMAIL=your.email@gmail.com
GMAIL_PASSWORD=your_app_password
GMAIL_SMTP_SERVER=smtp.gmail.com
GMAIL_SMTP_PORT=587
Use it in your code:
from email_sender.config import ConfigManager
config_manager = ConfigManager.from_file("gmail_config.txt")
sender = GmailSender(
email=config_manager.config.email,
password=config_manager.config.password
)
3. Direct Parameters
from email_sender import GmailSender
sender = GmailSender(
email="your.email@gmail.com",
password="your_app_password"
)
API Reference
GmailSender Class
Constructor
GmailSender(email=None, password=None)
email(str, optional): Gmail email address. If not provided, reads fromGMAIL_EMAILenvironment variable.password(str, optional): Gmail app password. If not provided, reads fromGMAIL_PASSWORDenvironment variable.
Methods
send_email(to_emails, subject, message, html_message=None, attachments=None)
Send an email with advanced options.
Parameters:
to_emails(str or list): Recipient email address(es)subject(str): Email subjectmessage(str): Plain text message bodyhtml_message(str, optional): HTML message bodyattachments(list, optional): List of file paths to attach
Returns: bool - True if successful
send_simple_email(to_email, subject, message)
Send a simple text email to a single recipient.
Parameters:
to_email(str): Recipient email addresssubject(str): Email subjectmessage(str): Plain text message body
Returns: bool - True if successful
test_connection()
Test the connection to Gmail SMTP server.
Returns: bool - True if connection successful
Exception Classes
EmailSenderError: Base exception classAuthenticationError: Raised when Gmail authentication failsSendError: Raised when email sending failsConfigurationError: Raised when configuration is invalid
Examples
See the examples/ directory for complete working examples:
basic_example.py: Simple email sending using environment variablesadvanced_example.py: HTML emails with attachments and multiple recipientsconfig_example.py: Different configuration methods
Error Handling
from email_sender import GmailSender, AuthenticationError, SendError
try:
sender = GmailSender()
sender.test_connection()
success = sender.send_simple_email(
to_email="recipient@example.com",
subject="Test Email",
message="Hello, World!"
)
except AuthenticationError as e:
print(f"Authentication failed: {e}")
print("Check your email and app password")
except SendError as e:
print(f"Failed to send email: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
Security Best Practices
-
Use App Passwords: Never use your regular Gmail password. Always use Gmail App Passwords.
-
Environment Variables: Store credentials in environment variables, not in your code.
-
Config Files: If using config files, add them to
.gitignoreto avoid committing credentials. -
Permissions: Keep your app passwords secure and rotate them regularly.
Common Issues & Solutions
Authentication Error (535)
Problem: smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted')
Solutions:
- Ensure you're using an App Password, not your regular Gmail password
- Check that 2-Factor Authentication is enabled on your Gmail account
- Verify the email address is correct
- Try generating a new App Password
Connection Issues
Problem: Connection timeouts or failures
Solutions:
- Check your internet connection
- Ensure port 587 is not blocked by your firewall
- Try using a different network
- Verify Gmail SMTP settings
File Attachment Issues
Problem: Attachments not working
Solutions:
- Check that file paths exist and are accessible
- Ensure files are not too large (Gmail has a 25MB limit)
- Verify file permissions
Development
Running Examples
# Set your credentials
export GMAIL_EMAIL="your.email@gmail.com"
export GMAIL_PASSWORD="your_app_password"
# Run examples
python examples/basic_example.py
python examples/advanced_example.py
python examples/config_example.py
Testing
# Install development dependencies
pip install -e ".[dev]"
# Run tests (when available)
pytest
# Code formatting
black email_sender/
black examples/
# Type checking
mypy email_sender/
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
If you encounter any issues or have questions:
- Check the Common Issues section
- Look at the examples for usage patterns
- Open an issue on GitHub
Changelog
v1.0.0
- Initial release
- Gmail SMTP support
- HTML email support
- File attachments
- Multiple recipients
- Configuration management
- Comprehensive error handling
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mailworks-1.0.0.tar.gz.
File metadata
- Download URL: mailworks-1.0.0.tar.gz
- Upload date:
- Size: 11.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d4abad6c46a101a633f04ecfbf790389eb938afd19393d30027d971bf05995c0
|
|
| MD5 |
59de0d633609709a579d8c938172cab0
|
|
| BLAKE2b-256 |
cdee78f624334b6cf2c7e719c29193eb11eae6ae785c22dfdbbbddf3ea63e362
|
File details
Details for the file mailworks-1.0.0-py3-none-any.whl.
File metadata
- Download URL: mailworks-1.0.0-py3-none-any.whl
- Upload date:
- Size: 9.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ff474e9849eab1c0860a5c19b67383b9a36a73e9d853aa87caa9ecbe0fb9c57e
|
|
| MD5 |
94b9ec277982d0ed02a4358c6efe5024
|
|
| BLAKE2b-256 |
b6e0ff9eac3cf49b8eeb7ce7881a415b621f1748d83313d0da9084ed99119fd8
|