HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Example Python Code to Send an Email

Sending emails programmatically is a common task in many applications. Python makes this process straightforward using builtin libraries like `smtplib` and `email`.

The example code provided demonstrates how to send an email by connecting to an SMTP server. It includes setting up email account credentials, creating a multipart message, and sending it securely. This approach can be adapted for various needs, such as automated notifications or user communication.

Using smtplib and email libraries

Let’s see a simple Python code example for sending an email using the `smtplib` and `email` libraries.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_email):
# Email account credentials
from_email = "[email protected]"
password = "your_password"

# Create a multipart message
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject

# Attach the email body
msg.attach(MIMEText(body, 'plain'))

try:
# Set up the SMTP server and send the email
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls() # Upgrade the connection to a secure encrypted SSL/TLS connection
server.login(from_email, password)
server.sendmail(from_email, to_email, msg.as_string())
server.quit() # Close the connection
print("Email sent successfully.")
except Exception as e:
print(f"Failed to send email. Error: {e}")

# Example usage
send_email("Test Subject", "This is a test email body.", "[email protected]")

StepbyStep Explanation

1. Import Required Libraries

  • `import smtplib`: This imports the `smtplib` library, which is used for sending emails using the SMTP protocol.
  • `from email.mime.text import MIMEText`: This imports `MIMEText`, which is used to create the body of the email.
  • `from email.mime.multipart import MIMEMultipart`: This imports `MIMEMultipart`, which allows you to create a multipart message (e.g., an email with both text and attachments).

2. Define the `send_email` Function

  • `def send_email(subject, body, to_email):`: This defines a function `send_email` that takes the subject, body, and recipient’s email address as parameters.

3. Set Email Account Credentials

  • `from_email = “[email protected]”`: Replace this with the email address you are sending from.
  • `password = “your_password”`: Replace this with your email account’s password. For security, consider using environment variables or a secure method for storing passwords.

4. Create a Multipart Message

  • `msg = MIMEMultipart()`: Create a new multipart email message.
  • `msg[‘From’] = from_email`: Set the sender’s email address.
  • `msg[‘To’] = to_email`: Set the recipient’s email address.
  • `msg[‘Subject’] = subject`: Set the email subject.

5. Attach the Email Body

  • `msg.attach(MIMEText(body, ‘plain’))`: Attach the email body to the message, specifying that the body is plain text.

6. Send the Email

  • `try:`: Start a block of code that might throw an exception. If an error occurs, the code inside `except` will run.
  • `server = smtplib.SMTP(‘smtp.example.com’, 587)`: Create an SMTP server object, replace `’smtp.example.com’` with your email provider’s SMTP server and `587` is the port for TLS encryption.
  • `server.starttls()`: Upgrade the connection to a secure, encrypted connection.
  • `server.login(from_email, password)`: Log in to the email server with your credentials.
  • `server.sendmail(from_email, to_email, msg.as_string())`: Send the email using the sender’s address, recipient’s address, and the email message.
  • `server.quit()`: Close the connection to the SMTP server.
  • `print(“Email sent successfully.”)`: Print a success message.
  • `except Exception as e:`: If an error occurs, this block catches the exception.
  • `print(f”Failed to send email. Error: {e}”)`: Print an error message with the exception details.

7. Example Usage

  • `send_email(“Test Subject”, “This is a test email body.”, “[email protected]”)`: Call the `send_email` function with a test subject, body, and recipient email address.

Summary

  • Step 1: Import necessary libraries for sending emails.
  • Step 2: Define a function to handle the email sending process.
  • Step 3: Set up email account credentials.
  • Step 4: Create a multipart email message.
  • Step 5: Attach the email body to the message.
  • Step 6: Set up and connect to the SMTP server, send the email, and handle any errors.
  • Step 7: Use the function to send an email with specified details.

This code provides a basic example of how to send an email using Python. Be sure to replace placeholder values with your actual email provider’s SMTP details and credentials.

It’s simple.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Example Code to Check Internet Connection
Up Next
Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.