How to Send Emails Using SMTP in Python with smtplib

You can send emails using Python’s built-in smtplib library, which supports the Simple Mail Transfer Protocol (SMTP). Here’s a step-by-step guide:


Steps to Send an Email:

  1. Import Libraries: Use smtplib for sending emails and email library to format the email.
  2. Set Up SMTP Server: Connect to your email provider’s SMTP server.
  3. Log In: Authenticate using your email and password.
  4. Compose the Email: Use the email.message module to craft the email.
  5. Send the Email: Use smtplib to send the email
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Email details
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_email_password"

# Create the email
subject = "Test Email"
body = "This is a test email sent using Python."

# Set up the MIME
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Attach the body
message.attach(MIMEText(body, "plain"))

# Connect to the SMTP server
try:
    with smtplib.SMTP("smtp.gmail.com", 587) as server:  # Gmail SMTP server
        server.starttls()  # Secure the connection
        server.login(sender_email, password)  # Log in to the server
        server.sendmail(sender_email, receiver_email, message.as_string())  # Send the email
    print("Email sent successfully!")
except Exception as e:
    print(f"Failed to send email: {e}")

Key Points:

  1. SMTP Server and Port:

    • Gmail: smtp.gmail.com and port 587
    • Outlook: smtp.office365.com and port 587
    • Yahoo: smtp.mail.yahoo.com and port 587
  2. Enable Access for Less Secure Apps: Some email providers require you to enable access for less secure apps or use app-specific passwords for SMTP.

  3. Secure Connections:

    • Use server.starttls() for encrypted connections.
    • Consider using smtplib.SMTP_SSL() for secure connection on port 465.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top