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.
import smtplibfrom email.message import EmailMessagedef 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 emailsend_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.
Use sandbox mode to safely test your Python email integration:
Copy
import smtplibfrom email.message import EmailMessagedef 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.