Sending Emails with SMTP in Python

Send emails through AhaSend’s SMTP servers using Python’s built-in smtplib and email modules. This guide covers everything from basic setup to advanced features like HTML content, attachments, and custom headers.

Prerequisites

Before you begin, ensure you have:
Need SMTP Credentials? If you haven’t created SMTP credentials yet, check out our SMTP Credentials guide for step-by-step instructions.

Built-in Modules

Python’s standard library includes everything you need for SMTP:

smtplib Module

Purpose: SMTP client session object
Features: Connection, authentication, sending
Security: STARTTLS support
Import: import smtplib

email Module

Purpose: Email message construction
Features: MIME, attachments, HTML
Classes: EmailMessage, MIMEMultipart
Import: from email.message import EmailMessage

Connection Settings

Use these settings for all Python SMTP configurations with AhaSend:

Primary Server

Host: send.ahasend.com
Ports: 587 (recommended), 25, 2525
Security: STARTTLS
Authentication: Required

US Server

Host: send-us.ahasend.com
Ports: 587 (recommended), 25, 2525
Security: STARTTLS
Authentication: Required

Basic Email Examples

import smtplib
from email.message import EmailMessage

def send_plain_text_email():
    # SMTP server configuration
    smtp_server = "send.ahasend.com"
    smtp_port = 587
    smtp_username = "YOUR_SMTP_USERNAME"
    smtp_password = "YOUR_SMTP_PASSWORD"

    # Email details
    from_addr = "[email protected]"
    to_addr = "[email protected]"
    subject = "Welcome to our platform!"
    body = "Thanks for signing up. We're excited to have you!"

    # Create the email message
    msg = EmailMessage()
    msg.set_content(body)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr

    # Connect to the SMTP server and send
    try:
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()  # Secure the connection
        server.login(smtp_username, smtp_password)
        server.send_message(msg)
        server.quit()
        print("Email sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")

# Send the email
send_plain_text_email()
Pro Tip: Python’s built-in modules are powerful and reliable. Use context managers for connection handling, always provide both HTML and text versions, and implement proper error handling with retry logic. Start with sandbox mode during development and use environment variables for credentials.

Testing with Sandbox Mode

Use sandbox mode to safely test your Python email integration:
import smtplib
from email.message import EmailMessage

def send_sandbox_email():
    # SMTP server configuration
    smtp_server = "send.ahasend.com"
    smtp_port = 587
    smtp_username = "YOUR_SMTP_USERNAME"
    smtp_password = "YOUR_SMTP_PASSWORD"

    # Email details
    from_addr = "[email protected]"
    to_addr = "[email protected]"
    subject = "Sandbox Test Email"

    # Create the email message
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr

    # Enable sandbox mode
    msg['AhaSend-Sandbox'] = 'true'
    msg['AhaSend-Sandbox-Result'] = 'deliver'

    msg.set_content("This email is sent in sandbox mode for testing.")

    # Connect and send
    try:
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()
        server.login(smtp_username, smtp_password)
        server.send_message(msg)
        server.quit()
        print("Sandbox email sent successfully!")
    except Exception as e:
        print(f"Failed to send sandbox email: {e}")

send_sandbox_email()
Sandbox Benefits: Emails sent in sandbox mode are free, trigger webhooks normally, and never actually deliver to recipients - perfect for development and testing.

Environment Variables & Best Practices

Using Environment Variables

smtplib with environment variables
import smtplib
import os
from email.message import EmailMessage

def send_email_with_env_vars():
    # Load configuration from environment variables
    smtp_server = os.getenv('SMTP_HOST', 'send.ahasend.com')
    smtp_port = int(os.getenv('SMTP_PORT', '587'))
    smtp_username = os.getenv('SMTP_USERNAME')
    smtp_password = os.getenv('SMTP_PASSWORD')
    from_email = os.getenv('FROM_EMAIL')
    from_name = os.getenv('FROM_NAME', 'Your Company')

    # Validate required environment variables
    required_vars = [smtp_username, smtp_password, from_email]
    if not all(required_vars):
        print("Missing required environment variables:")
        print("Set: SMTP_USERNAME, SMTP_PASSWORD, FROM_EMAIL")
        return False

    # Create email message
    msg = EmailMessage()
    msg['Subject'] = "Environment Variables Test"
    msg['From'] = f'"{from_name}" <{from_email}>'
    msg['To'] = "[email protected]"
    msg.set_content("This email uses environment variables for configuration.")

    # Send email
    try:
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()
        server.login(smtp_username, smtp_password)
        server.send_message(msg)
        server.quit()
        print("Email sent using environment variables!")
        return True
    except Exception as e:
        print(f"Failed to send email: {e}")
        return False

# Usage
if __name__ == "__main__":
    send_email_with_env_vars()

Resources