Last modified: Jun 04, 2023 By Alexander Williams

Python: A Guide to Sending Emails

In this article, we'll learn how to send mail in Python.

Prerequisites

Before we dive into the code, you will need to have the following libraries installed by running the following command:

pip install smtplib email

The smtplib module provides a simple way to send emails using the Simple Mail Transfer Protocol (SMTP).

The email module provides classes for creating, formatting, and parsing email messages. It is used with the smtplib module for sending emails, as shown in the previous example.

Sending an Email

If you plan to use the Gmail server, there are a few settings you need to enable to proceed. Here's what you need to do:

  1. Firstly, sign in to your Gmail account.
  2. Access your account settings in the top-right corner of the Gmail interface.
  3. Look for the tab labelled "Forwarding and POP/IMAP" and click on it.
  4. In the "POP Download" section, ensure that either "Enable POP for all mail" or "Enable POP for mail that arrives from now on" is selected. This step allows you to download your emails using POP.
  5. Scroll down to the "IMAP Access" section and select "Enable IMAP". Enabling IMAP grants you access to your Gmail account through IMAP.
  6. Once you've made these changes, remember to save them.

However, in the following code, will show how send an email in a example:

# Importing the Required Libraries
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Setting up the Email Details
sender_email = "your_email@gmail.com"
receiver_email = "recipient_email@example.com"
subject = "Hello from Python!"
body = "Dear recipient,\n\nI hope this email finds you well. This is an automated email sent using Python. Thank you.\n\nRegards,\nSender"

# Creating the Email Object
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Adding the Email Body
message.attach(MIMEText(body, "plain"))

# Establishing the SMTP Connection:
smtp_server = "smtp.gmail.com"
smtp_port = 587

with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender_email, "your_password")
    server.send_message(message)

Ensure that you follow these steps:

  • Define the email sender, recipient(s), subject, and body
  • Replace "your_password" with your actual email password or use app-specific passwords for increased security.

Conclusion

Congratulations! You have learned how to send emails using Python. Automating the email-sending process can save time and streamline your communication efforts. Experiment with different email content, recipients, and SMTP servers to cater to your needs.

If you're interested in learning how to send emails with attachments, I recommend checking out the following article for detailed guidance:

Send Email with Attachment or Multi Attachments in Python