Skip to main content

Command Palette

Search for a command to run...

Activity 48: Documentation of Python SMTP

Published
4 min read

Activity 48: Documentation of Python SMTP

Overview:

Python's smtplib is a built-in library that allows you to send emails using the Simple Mail Transfer Protocol (SMTP). This protocol is the standard for email transmission on the internet. With smtplib, you can connect to an SMTP server, send emails, and handle email messages programmatically.

This documentation will provide an overview of how to use smtplib in Python to send emails. We will cover the basic setup, usage, and common use cases.


1. Setting Up SMTP in Python

Before sending an email, you need to connect to an SMTP server and authenticate using your email credentials. Below is a basic overview of the process:

  1. Connect to the SMTP Server: You need to know the SMTP server and port number of the email provider.

  2. Login to the SMTP Server: Provide your credentials (email and password) to log in.

  3. Send an Email: Create the email message, specify the recipient and subject, and send the email.

  4. Close the Connection: Always close the connection to the SMTP server after the email is sent.


2. Code Example: Sending Email Using SMTP

Below is an example of a simple Python script using smtplib to send an email:

from flask import Flask, request, jsonify
from flask_mail import Mail, Message
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

app = Flask(__name__)

# Configure the Flask-Mail extension
app.config['MAIL_SERVER'] = os.getenv('EMAIL_HOST')
app.config['MAIL_PORT'] = int(os.getenv('EMAIL_PORT'))
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.getenv('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.getenv('EMAIL_PASSWORD')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('EMAIL_SENDER')

# Initialize Mail object
mail = Mail(app)

@app.route('/send-email', methods=['POST'])
def send_email():
    try:
        # Retrieve JSON data from the request
        data = request.get_json()
        message_body = data.get('message')
        recipient_email = data.get('email')

        if not message_body or not recipient_email:
            return jsonify({'error': 'Missing message or email'}), 400

        # Compose the email message
        msg = Message(subject="Message from Flask App",
                      recipients=[recipient_email],
                      body=message_body)

        # Send the email
        mail.send(msg)

        return jsonify({'success': True, 'message': 'Email sent successfully'}), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)

3. Key Concepts and Terminology

  • SMTP Server: The server that handles email transmission. Examples: Gmail (smtp.gmail.com), Yahoo (smtp.mail.yahoo.com), and Outlook (smtp-mail.outlook.com).

  • Port 587: The standard port for sending email over SMTP with TLS encryption.

  • TLS (Transport Layer Security): A protocol that encrypts the communication between the email client and the server to ensure security.

  • MIME (Multipurpose Internet Mail Extensions): A standard that allows email to include text in different formats, images, and attachments. The MIMEMultipart and MIMEText classes are used to create email messages in these formats.


4. Common SMTP Servers and Ports

Different email providers offer different SMTP configurations. Below are some examples:

Email ProviderSMTP ServerSMTP PortTLS/SSL
Gmailsmtp.gmail.com587TLS
Yahoosmtp.mail.yahoo.com587TLS
Outlook (Microsoft)smtp-mail.outlook.com587TLS
Zoho Mailsmtp.zoho.com587TLS
SendGridsmtp.sendgrid.net587TLS

5. Handling Email Attachments

You can also send emails with attachments using smtplib. To do this, use the MIMEBase class in conjunction with the email.mime modules.

Here’s how you would send an email with an attachment:

from email.mime.base import MIMEBase
from email import encoders

def send_email_with_attachment(subject, recipient_email, message, attachment_path):
    try:
        msg = MIMEMultipart()
        msg['From'] = SENDER_EMAIL
        msg['To'] = recipient_email
        msg['Subject'] = subject
        msg.attach(MIMEText(message, 'plain'))

        # Open the attachment file in binary mode
        with open(attachment_path, "rb") as attachment:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment.read())
            encoders.encode_base64(part)

            # Add header to specify the file attachment
            part.add_header('Content-Disposition', f'attachment; filename={attachment_path}')
            msg.attach(part)

        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()
        server.login(SENDER_EMAIL, SENDER_PASSWORD)
        server.sendmail(SENDER_EMAIL, recipient_email, msg.as_string())
        server.quit()

        print("Email with attachment sent successfully!")

    except Exception as e:
        print(f"Error sending email: {e}")

# Usage example
send_email_with_attachment("Test Subject", "recipient_email@example.com", 
                            "This is a test message with an attachment.", 
                            "test_attachment.txt")

6. Error Handling and Debugging

When using smtplib, errors can occur due to network issues, authentication failure, or incorrect email formats. The most common exceptions are:

  • smtplib.SMTPAuthenticationError: Raised if the login credentials are incorrect.

  • smtplib.SMTPConnectError: Raised if the connection to the SMTP server fails.

  • smtplib.SMTPRecipientsRefused: Raised if the recipient's email address is invalid.

  • smtplib.SMTPDataError: Raised if there is an issue with the message content.

It’s good practice to include try-except blocks to catch exceptions and print helpful error messages.