Skip to main content

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:
  • Python installed on your system (Download Python)
  • Python 3.6 or higher (recommended)
  • Basic knowledge of Python programming
  • Domain verified in your AhaSend account
  • SMTP credentials created (username and password)
  • Access to your AhaSend dashboard for credential management
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

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:
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

Resources

Python smtplib Documentation

Official Python smtplib module documentation

Python email Documentation

Official Python email module documentation

Python.org

Official Python programming language documentation

AhaSend Support

Get help from our engineering team