Blog

How to send emails in python

Sending emails programmatically using Python is a common task that can streamline communication workflows, automate notifications, and integrate email functionality into larger applications. Whether you’re looking to send simple text messages, include attachments, or use advanced features like SMTP authentication, Python provides powerful libraries and tools to accomplish these tasks efficiently. In this comprehensive guide, we will explore the various methods to send emails in Python, including practical examples, best practices, and useful tips to ensure secure and reliable email delivery in 2025.

Understanding the Basics of Email Sending in Python

At its core, sending an email in Python involves connecting to an email server via the Simple Mail Transfer Protocol (SMTP). SMTP is the standard communication protocol for email transmission across the Internet. Python’s smtplib library offers built-in support for SMTP, making it straightforward to send emails from your scripts or applications.

Key Components for Sending Emails

  • SMTP Server: The server responsible for sending emails, such as Gmail, Outlook, or custom mail servers.
  • Authentication: Usually involves a username and password to authenticate with the SMTP server, especially for secured servers.
  • Email Content: Comprising sender, recipient(s), subject, message body, and optional attachments.
  • Security: Use of SSL/TLS encryption to protect login credentials and email content during transmission.

Setting Up Your Environment

Before diving into code, ensure you have Python installed (version 3.6+ is recommended). No additional libraries are necessary for basic email sending, as smtplib and email are included in the standard library. However, for more complex tasks, third-party libraries like secure-smtplib or email-validator can be helpful.

Basic Example: Sending a Simple Text Email


import smtplib

# SMTP server configuration
smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "your_email@gmail.com"
password = "your_app_password"

# Email content
receiver_email = "recipient@example.com"
subject = "Test Email from Python"
body = "Hello! This is a simple email sent using Python."

# Create the email message
message = f"""
Subject: {subject}
From: {sender_email}
To: {receiver_email}

{body}
"""

try:
    # Connect to the SMTP server
    with smtplib.SMTP(smtp_server, port) as server:
        server.starttls()  # Secure the connection
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message)
    print("Email sent successfully!")
except Exception as e:
    print(f"An error occurred: {e}")

Note: For Gmail accounts, you need to generate an app password or enable less secure app access if applicable (not recommended). Always prefer app passwords for security.

Sending HTML Emails with Attachments

Most modern emails contain HTML content or attachments. To send such emails, Python’s email library provides flexible classes to construct complex messages.


import smtplib
from email.message import EmailMessage

# Email details
sender = "your_email@gmail.com"
password = "your_app_password"
receiver = "recipient@example.com"

# Create the email message
msg = EmailMessage()
msg['Subject'] = "HTML Email with Attachment"
msg['From'] = sender
msg['To'] = receiver
msg.set_content("This is a fallback plain text message.")
msg.add_alternative("""

    
        

Hello from Python!

This is an HTML email.

""", subtype='html') # Add attachment with open('example.pdf', 'rb') as f: file_data = f.read() file_name = 'example.pdf' msg.add_attachment(file_data, maintype='application', subtype='pdf', filename=file_name) # Send email try: with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() server.login(sender, password) server.send_message(msg) print("HTML email with attachment sent successfully!") except Exception as e: print(f"Error: {e}")

For large or complex email projects, consider using third-party APIs like SendGrid, Mailgun, or Amazon SES, which offer more reliable delivery and analytics.

Security Best Practices for Sending Emails in Python

Best Practice Description
Use App Passwords Generate app-specific passwords instead of your main account password, especially with Gmail, to enhance security.
Encrypt Connection Always use starttls() or SSL/TLS encryption to secure login credentials and email content.
Handle Exceptions Wrap your email-sending code in try-except blocks to gracefully handle network errors or authentication issues.
Validate Email Addresses Use libraries like email-validator to ensure email addresses are correctly formatted before sending.
Avoid Hardcoding Credentials Store sensitive information in environment variables or secure vaults, not directly in code.

Advanced Topics: SMTP with OAuth2 and Third-Party Services

In 2025, many email providers prioritize OAuth2 authentication for enhanced security. Python libraries such as google-auth facilitate OAuth2 implementation with Gmail. Additionally, integrating third-party services like Pyway’s next-gen Python application development services can help develop scalable email solutions with advanced features like analytics, delivery optimization, and automation.

Here’s a quick overview of using OAuth2 with Gmail in Python:


from google.oauth2 import service_account
import smtplib

# Load the service account credentials
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
SERVICE_ACCOUNT_FILE = 'path/to/credentials.json'

credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# Obtain OAuth2 token
access_token = credentials.token

# Connect to SMTP with OAuth2
auth_string = 'user={}1auth=Bearer {}11'.format('your_email@gmail.com', access_token)

with smtplib.SMTP('smtp.gmail.com', 587) as server:
    server.starttls()
    server.docmd('AUTH', 'XOAUTH2 ' + auth_string)
    # Prepare and send message
    # ...

*Note:* Implementing OAuth2 is more complex and requires setting up Google Cloud credentials, but it significantly increases security and compliance with modern standards.

Summary of Tools and Libraries

Library/Tool Purpose Link
smtplib Standard Python library for SMTP protocol Official Documentation
email Constructs email messages with attachments and HTML content Official Documentation
email-validator Validates email address syntax GitHub Repository
Third-party APIs Enhanced email delivery, tracking, and automation See providers like SendGrid, Mailgun

Final Tips for Reliable Email Sending

  1. Use verified SMTP servers and ensure your IP isn’t blacklisted.
  2. Implement a retry mechanism for failed email attempts.
  3. Monitor bounce-backs and delivery reports for troubleshooting.
  4. Maintain an email whitelist to improve deliverability.
  5. Regularly update your libraries and dependencies to patch security vulnerabilities.

For developers seeking to build robust email functionalities integrated into larger Python applications, exploring advanced application development services like Pyway’s next-generation Python application development services can provide tailored solutions, scalability, and ongoing support.