A Python script to send emails with file attachments via Gmail's SMTP server.
- Send emails with file attachments (PDF, images, documents, etc.)
- Secure TLS connection using port 587
- Clean error handling for file operations and email sending
- Professional email formatting with body text
- Support for various file types
- Python 3.x
- Gmail account with App Password enabled
- Enable 2-Factor Authentication on your Google Account
- Generate an App Password:
- Go to: https://myaccount.google.com/apppasswords
- Select "Mail" → Choose device → Generate
- Copy the 16-character password
Edit these variables in the script:
sender_email = "your_email@gmail.com"
receiver_email = "recipient@example.com"
password = "your_app_password_here"
file_path = "path/to/your/file.pdf" # Update with actual file pathpython email_attachment_sender.py- PDF documents (
.pdf) - Images (
.jpg,.png,.gif) - Documents (
.docx,.txt,.xlsx) - Any file readable in binary mode
# Windows
file_path = "C:\\Users\\Name\\Documents\\file.pdf"
file_path = r"D:\Files\document.pdf"
# Mac/Linux
file_path = "/Users/name/Documents/file.pdf"
file_path = "~/Documents/image.jpg"# ❌ NEVER do this in production:
password = "your_password_here" # Hardcoded password
# ✅ Recommended alternatives:
# 1. Use environment variables
import os
password = os.getenv("GMAIL_APP_PASSWORD")
# 2. Use input() for local testing
password = input("Enter app password: ")
# 3. Use configuration files (.env)- Remove or replace actual email addresses
- Replace real passwords with placeholders
- Use
.gitignoreto exclude config files
| Issue | Solution |
|---|---|
FileNotFoundError |
Check file path, use raw strings (r"path") for Windows |
Authentication failed |
Verify App Password is correct, enable 2FA |
SMTPAuthenticationError |
Allow less secure apps (temporarily) or use App Password |
File attachment fails |
Check file permissions, ensure file exists |
Connection refused |
Check firewall, try port 465 with SMTP_SSL() |
If port 587 fails, use this alternative:
# Replace the sending block with:
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())Edit these sections to customize:
message["Subject"] = "Your Custom Subject"
body = """Your custom email body text here..."""- File attachment validation
- Connection error reporting
- Authentication feedback
- Success/failure notifications with emojis
- Test with a small text file first
- Verify the file opens correctly before sending
- Send to yourself first for testing
- Always use App Passwords, never regular passwords
- Store credentials securely (env vars, keyring, etc.)
- Validate file paths before attempting to attach
- Add size limits for large attachments
- Include informative email subjects and body text
- Gmail has a 25MB attachment limit
- Rate limiting may apply for multiple emails
- Some file types may be blocked by recipient's email server
Educational use only. Comply with Gmail's Terms of Service and anti-spam regulations.
- 2-Factor Authentication enabled
- App Password generated for "Mail"
- Correct file path (use
os.path.exists()to verify) - Internet connection active
- No special characters in file name causing issues
- File not open in another program